Validating ASCII character set
20 January 2008In this post, I will write about how to validate characters of ASCII characterset.
ASCII is a well know character set. It is a 7 bit character set and represents 128 characters. The printable character codes range from 33 to 126 inclusive. Sometimes you want to make sure that your strings do not contains non ASCII printable character. This is easy and can be done by writing a method for this.
Review the static method below. It takes an ArrayList of String type and after removing the non ASCII and non printable characters, it return the updated ArrayList. All the non printable and non ASCII characters are replaced by null.
public static ArrayList<String> valiateAsciiSet(ArrayList <String>arraylist){ ArrayList<String> tmpList = new ArrayList<String>(); String str = ""; for(int j=0; j < arraylist.size();j++) { str = arraylist.get(j); String resultantString = ""; for(int i=0;i<str.length();i++){ int charCode = (int)str.charAt(i); if(charCode>=33 && charCode <=126) resultantString += str.charAt(i); else resultantString += null; } tmpList.add(resultantString); } return tmpList; }
Now to show how it works, lets declare an ArrayList, put some string with non ASCII characters and pass the ArrayList to the method above.
ArrayList <String>arrayList = new ArrayList<String> (); arrayList.add("ABCÄ d_"); arrayList.add("here I am "); arrayList.add("-_----mouse hÄÄÄööunt "); arrayList = valiateAsciiSet(arrayList); for(String strAscii: arrayList) System.out.println(strAscii);
Output:
ABCnullnulld_ herenullInullamnull -_----mousenullhnullnullnullnullnulluntnull
The non ASCII and non printable characters are replaced by null.
I hope this helps.
Related Posts:
- Handling ASCII character set in Java (I)
- Handling ASCII character set in Java (II)
- Handling ASCII character set in Java (III)
- Character Streams
- JSP Tag - I
- Reading an ASCII file (BufferedReader)
- HashMap example - 1
- Performance Issues (StringTokenizer)
- Using the JAXP validation framework
- Taking inputs from users
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Validating ASCII character set