Detecting Alphanumeric Characters in a String

Detecting Alphanumeric Characters in a String

Java provides a convenient function for detecting whether a character is alphanumeric (1-26 and 0-9) or not. This function is available in the class Character. Some of the other related methods include:

 public static boolean isDigit()
// Determines if the character is a digit (0-9)public static boolean isLetter()
// Determines if the character is a letter (a-z)public static boolean isLetterOrDigit()
// Determines if the character is alphanumeric.

You can extract the alphanumeric characters from a text string by using the following method:

 1.     public String testAlphaNumeric (String[] str) {2. 3.       StringBuffer sb = new StringBuffer();4.       int length = str.length();5. 6.       System.out.println("Input String = " + str);7. 8.       for (int i = 0; i 

The method testAlphaNumeric takes a String argument and returns a string that is extracted from the input string and stripped of all alphanumeric characters. Lines 8-11 extract the characters into a StringBuffer. A new string is constructed from the StringBuffer and returned on line 13. On line 10, each character of the input string is checked to see if it is alphanumeric or not by using the method isLetterOrDigit. Note that isLetterOrDigit is a static method on the Character class and as a result no object of this class needs to be instantiated.


Share the Post: