Jump to Real's How-to Main page

Replace/remove character in a String

To replace all occurences of a given character :
String   tmpString = myString.replace( '\'', '*' );
System.out.println( "Original = " + myString );
System.out.println( "Result   = " + tmpString );
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);
}
Check this Optimize How-to for a more efficient String handling technique.

New with JDK1.4, the String class offers the replaceAll() method that can be used with String or char.

String.replaceAll("\n", "");    // Remove all \n
String.replaceAll("\n", "\r");  // Replace \n by \r
Thanks to jsanza for the tip!
If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2007
[ home ]