Replace/remove character in a String

/, Programming & Code/Replace/remove character in a String

Replace/remove character in a String

To replace all occurences of a given character :

String.replaceAll("n", ""); // Remove all n
String.replaceAll("n", "r"); // Replace n by r

To replace a character at a specified position :

public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0,pos) + c + s.substring(pos+1);
}

To remove a character :

public static String removeChar(String s, char c) {
String r = "";
for (int i = 0; i < s.length(); i ++) {
if (s.charAt(i) != c) r += s.charAt(i);
}
return r;
}

To remove a character at a specified position:

public static String removeCharAt(String s, int pos) {
return s.substring(0,pos)+s.substring(pos+1);
}

Similar Posts:

By |2009-09-23T03:38:09+00:00April 4th, 2007|Miscellaneous, Programming & Code|0 Comments

About the Author:

Alvin Poh lives in Singapore, and is interested in marketing, techy stuff, and likes to just figure out how the two can work with each other. He can also be found on Google+.

Leave A Comment


*