Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: All
Dec 17, 1998

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.
Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date