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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several