Real'sHowTo AddThis Feed Button
Custom Search

Replace/remove character in a StringTag(s): String/Number


To replace all occurences of a given character :
String   tmpString = myString.replace( '\'', '*' );

System.out.println( "Original = " + myString );
System.out.println( "Result   = " + tmpString );

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

replaceAll() accepts a regex as argument so it can be very powerful.

To delete all non-digit in a String

    System.out.println(
        "@*1#^2$@!34#5ajs67>?<{8_(9SKJDH".replaceAll("\\D", ""));

    // output : 123456789

If your project already depends on Apache Commons then StringUtils provides many methods to manipulate String objects, no need to reinvent the wheel!
import org.apache.commons.lang.StringUtils;
...
foo = StringUtils.replace(foo, "bar", "baz");
// replace in foo the occurrence of bar" by "baz"

To replace a character at a specified position :
public static String replaceCharAt(String s, int pos, char c) {
  StringBuffer buf = new StringBuffer( s );
  buf.setCharAt( pos, c );
  return buf.toString( );
}
To remove a character :
public static String removeChar(String s, char c) {
  StringBuffer r = new StringBuffer( s.length() );
  r.setLength( s.length() );
  int current = 0;
  for (int i = 0; i < s.length(); i ++) {
     char cur = s.charAt(i);
     if (cur != c) r.setCharAt( current++, cur );
  }
  return r.toString();
}
To remove a character at a specified position:
public static String removeCharAt(String s, int pos) {
   StringBuffer buf = new StringBuffer( s.length() - 1 );
   buf.append( s.substring(0,pos) ).append( s.substring(pos+1) );
   return buf.toString();
}

Check this Optimize How-to for String handling techniques.
blog comments powered by Disqus


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-2014
[ home ]