devxlogo

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 < length; i++) {9.         char c = str.charAt(i);10.      if (Character.isLetterOrDigit(c))11.         sb.append(c);    12.    }13.    return new String(sb);14.  }

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist