Friday, April 04, 2008

StringTokenizer separater issue with special charecters

public class Tokenizer {

public static void main(String[] args) {

String longStr = "33068|~|Disa+bled|~|False==34296|~|Value|~|Yes";

String separator = "+";

StringTokenizer token = new StringTokenizer(longStr, separator);

String[] strList = longStr.split(separator);

for(int i=0; i < strList.length ; ++i)

{

System.out.println(strList[i]);

}

}

Hi ,

The above program is throwing an exeception because I am using '+' as delimeter . if we put '\\+' then it is working fine.

Problem is the separator is configurable and I don't know which data will come into this. Some times it may be one character and sometimes it may be

String which contains these meta characters. In those case I can't identify those and put \\ right… tell me is there any method to do this.



Solution :

"\\Q"+separator+"\\E";

If we use \\Q and \\E it will remove all the metacharacters in the string and it will take as it is…

$ in replacement text of string.

If you want to replace a part of the string with other string which consists a character $ in it, with normal replace/replaceAll will give error. To resolve it see following code.

String str = "asdf$fgh";
String str2 = "hghf-j-kjfi";
//Matcher m
str = str.replaceAll("\\$", "\\\\\\$");
str = str2.replaceAll("-j-", str);
System.out.println(str);