Replacing parts of Strings and Getting the nth character in a String


Replacing parts of Strings


Two ways to replace: by regex or by exact match.

Note : the original String object will be unchanged, the return value holds the changed String.

Exact match

Replace single character with another single character

String replace(char oldChar, char newChar)
  • Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String phrase = "butterfly";
System.out.println(phrase.replace('t', 'T'));

Result:

buTTerfly

Replace sequence of characters with another sequence of characters:

String replace(CharSequence target, CharSequence replacement)
  • Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String phrase = "cup of tea or coffee";
System.out.println(phrase.replace("of", "with"));

Result:

cup with tea or coffee

Regex

Note : the grouping uses the $ character to reference the groups, like $1.

Replace all matches:

String replaceAll(String regex, String replacement)
  • Replaces each substring of this string that matches the given regular expression with the given replacement.
String phrase = "exponential petal et al.";
System.out.println(phrase.replaceAll("(\\w*ental)", "$1lica"));

Result:

exponlica petal et al.

Replace first match only:

String replaceFirst(String regex, String replacement)
  • Replaces the first substring of this string that matches the given regular expression with the given replacement
String phrase = "bright light, light, bright light";
System.out.println(phrase.replaceFirst("light", "LIGHT"));
 

Result:

bright LIGHT, light, bright light

Getting the nth character in a String

String newStr = "Different Example";
System.out.println(newStr.charAt(0)); // First character "D"
System.out.println(newStr.charAt(1)); // Second character "i"
System.out.println(newStr.charAt(2)); // Third character "f"
System.out.println(newStr.charAt(newStr.length() - 1)); // Last character "e"

To get the nth character in a string, simply call charAt(n) on a String, where n is the index of the character you would like to retrieve

Note : index n is starting at 0, so the first element is at n=0.

Basic Programs