Created
April 13, 2015 22:21
-
-
Save lifeparticle/7f0491c50055535f6f1e to your computer and use it in GitHub Desktop.
Replace last occurrence of Character in a String using Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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