Share this page 

Strip certain characters from a StringTag(s): String/Number


This example keeps only a given set of accepted characters.
public class StringUtils {
  private StringUtils() {}

  public static String stripGarbage(String s) {
    String good =
      " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    String result = "";
    for ( int i = 0; i < s.length(); i++ ) {
        if ( good.indexOf(s.charAt(i)) >= 0 ) {
           result += s.charAt(i);
        }
    }
    return result;
  }


  public static void main(String args[]) {
     System.out.println (StringUtils.stripGarbage("A good String"));
     System.out.println (StringUtils.stripGarbage("String with !%garbage &*("));
     /*
     output :
        A good String
        String with garbage
     */
  }
}
NOTE: You may want to look at How-to optimize string operations

The following snippet will strip or keep from a given string the specified characters.

Thanks to T. GUIRADO for the idea

public class StringUtils {
  private StringUtils() {}

  /**
   * @param s   source string
   * @param toMatch  target character(s)
   * @param boolean  true=keep  false=strip
   **/
   public static String cleanUp
        ( String s, String sToMatch, boolean isToKeep ) {
     final int size = s.length();
     StringBuffer buf = new StringBuffer( size );
     if ( ! isToKeep ) {
       for ( int i = 0; i < size; i++ ){
         if ( sToMatch.indexOf(s.charAt(i) ) == -1 ){
           buf.append( s.charAt(i) );
         }
       }
     }
     else {
       for ( int i = 0; i < size; i++ ){
         if ( sToMatch.indexOf(s.charAt(i) ) != -1 ){
           buf.append( s.charAt(i) );
         }
       }
     }
     return buf.toString();
   }

   public static void main(String args[]) {
     System.out.println(cleanUp("realhowGARBhowtoAGE", "GARBAGE", false));
     System.out.println(cleanUp("THISrealIShowtoGOOD", "THISISGOOD", true));
     /*
      * output :
      *  realhowhowto
      *  THISISGOOD
      */
   }
}