Difference between String replace() and replaceAll()

In java.lang.String, the replace method either takes a pair of char’s or a pair of CharSequence‘s (of which String is a subclass, so it’ll happily take a pair of String’s). The replace method will replace all occurrences of a char or CharSequence. On the other hand, the first String arguments of replaceFirst and replaceAll are regular expressions (regex). Using the wrong function can lead to subtle bugs.

Java String to SHA1

UPDATEYou can use Apache Commons Codec (version 1.7+) to do this job for you. DigestUtils.sha1Hex(stringToConvertToSHexRepresentation) Thanks to @Jon Onstott for this suggestion. Old Convert your Byte Array to Hex String. Real’s How To tells you how. return byteArrayToHexString(md.digest(convertme)) and (copied from Real’s How To) public static String byteArrayToHexString(byte[] b) { String result = “”; for (int i=0; i < … Read more

Replace a character at a specific index in a string?

String are immutable in Java. You can’t change them. You need to create a new string with the character replaced. String myName = “domanokz”; String newName = myName.substring(0,4)+’x’+myName.substring(5); Or you can use a StringBuilder: StringBuilder myName = new StringBuilder(“domanokz”); myName.setCharAt(4, ‘x’); System.out.println(myName);

How to convert a String to CharSequence?

Since String IS-A CharSequence, you can pass a String wherever you need a CharSequence, or assign a String to a CharSequence: CharSequence cs = “string”; String s = cs.toString(); foo(s); // prints “string” public void foo(CharSequence cs) { System.out.println(cs); } If you want to convert a CharSequence to a String, just use the toString method that must be implemented by every concrete implementation of CharSequence.

How to use regex in String.contains() method in Java

String.contains String.contains works with String, period. It doesn’t work with regex. It will check whether the exact String specified appear in the current String or not. Note that String.contains does not check for word boundary; it simply checks for substring. Regex solution Regex is more powerful than String.contains, since you can enforce word boundary on … Read more

How to swap String characters in Java?

Since String objects are immutable, going to a char[] via toCharArray, swapping the characters, then making a new String from char[] via the String(char[]) constructor would work. The following example swaps the first and second characters: String originalString = “abcde”; char[] c = originalString.toCharArray(); // Replace with a “swap” function, if desired: char temp = c[0]; c[0] = c[1]; c[1] = temp; String swappedString = new … Read more