Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Replace last occurrence of Character in a String using Java
// beta
// Lisence Under GPL2
// Author: S.Mahbub-Uz-Zaman
public static String a = "test,test,test";
public static String replaceWith = " and ";
// using StringBuffer's replace method
public static void replaceLastCommaSB () {
StringBuffer sb = new StringBuffer(a);
sb.replace(a.lastIndexOf(","), a.lastIndexOf(",") + 1, replaceWith);
System.out.println(sb);
}
output: test,test and test
// using String's substring method
public static void replaceLastCommaSS () {
String temp = a.substring(0, a.lastIndexOf(",")) + replaceWith + a.substring(a.lastIndexOf(",") + 1);
System.out.println(temp);
}
output: test,test and test
// regular expression [work on progress]
public static void replaceLastCommaRE () {
String temp = a.replaceFirst(",", replaceWith);
System.out.println(temp);
}
output: test and test,test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.