Validating ASCII character set

20 January 2008

In 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.

del.icio.us:Validating ASCII character set  digg:Validating ASCII character set  spurl:Validating ASCII character set  wists:Validating ASCII character set  simpy:Validating ASCII character set  newsvine:Validating ASCII character set  blinklist:Validating ASCII character set  furl:Validating ASCII character set  reddit:Validating ASCII character set  fark:Validating ASCII character set  blogmarks:Validating ASCII character set  Y!:Validating ASCII character set  smarking:Validating ASCII character set  magnolia:Validating ASCII character set  segnalo:Validating ASCII character set  gifttagging:Validating ASCII character set

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

Leave a Reply