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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS