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);
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);
output: test,test and test
// regular expression [work on progress]
public static void replaceLastCommaRE () {
String temp = a.replaceFirst(",", replaceWith);
output: test and test,test

view raw
hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s