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)
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)
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)
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)
String phrase = "bright light, light, bright light"; System.out.println(phrase.replaceFirst("light", "LIGHT"));
Result:
bright LIGHT, light, bright light
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.
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions