View RSS Feed

My Java Tips

Validating ASCII character set

Rate this Entry
by , 11-17-2011 at 07:04 PM (3370 Views)
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.

Java Code:
	public static ArrayList valiateAsciiSet(ArrayList arraylist){

		ArrayList tmpList = new ArrayList();
		String str = "";

		for(int j=0; j < arraylist.size();j++)
		{
			str = arraylist.get(j);
			String resultantString = "";
			for(int i=0;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.

Java Code:
ArrayList arrayList = new ArrayList ();

arrayList.add("ABC d_");
arrayList.add("here I am ");
arrayList.add("-_----mouse hunt ");

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.

Submit "Validating ASCII character set" to Facebook Submit "Validating ASCII character set" to Digg Submit "Validating ASCII character set" to del.icio.us Submit "Validating ASCII character set" to StumbleUpon Submit "Validating ASCII character set" to Google

Comments