Replace/remove character in a String

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn

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:

More to explorer

how i started being a minimalist

How I Started Being A Minimalist

Once, I thought that all that mattered in life were the things that you possessed. Things like your car, house, watch, clothes.

Leave a Reply

Your email address will not be published. Required fields are marked *