Mar
06
Posted on 06-03-2006
Filed Under (Java) by Johan Känngård

Here is a simple method (actually two) for removing multiple characters from a String:


/**
 * Removes the specified characters from the supplied String.
 *
 * @param s the String to remove characters in.
 * @param a the characters to remove from the supplied String.
 * @return the String stripped from all the supplied characters.
 */
public static String removeChars(String s, char[] a) {
  StringBuffer r = new StringBuffer();
  for (int i = 0; i < s.length(); i ++) {
    if (!contains(s.charAt(i), a)) {
      r.append(s.charAt(i));
    }
  }
  return r.toString();
}

/**
 * Searches a char array for the specified character.
 *
 * @param c the char to find in the char array.
 * @param a the char array to search in.
 * @return true if the char is found in the char array,
 * false if not.
 */
public static boolean contains(char c, char[] a) {
  for (int i = 0; i < a.length; i++) {
    if (c == a[i]) {
      return true;
    }
  }
  return false;
}


The above can be used like this to check if a String is a valid phone number:

/**
 * Checks if the String is a valid phone number.
 * It is valid if it only contains numbers or any of the characters
 * +-() and space
 *
 * @param s the String to test for a valid phone number.
 * @return true if the supplied String is a valid phone number,
 * false if not.
 */
public boolean isValidPhoneNumber(String s) {
  char[] a = {'-', '+', '(', ')', ' '};

  try {
    Double.parseDouble(removeChars(s, a));
    return true;
  } catch (NumberFormatException e) {
    return false;
  }
}

Apache Jakarta Commons Lang StringUtils has a variant of the removeChars method above called replaceChars that also can be useful.
[tags]Java[/tags]

(1) Comment    Read More