Tuesday, February 7, 2012

String Manipulation in Java

Working with String like things in java is very common, and one of the common uses case. While we need to replace a substring inside a long String, we have couple of options in java.

Java "String" itself has methods like replace and replaceAll which we can use to replace a substring from the main string.

The other option is using StringBuilder  which has method like replace(start, end,str);  Which is better then the formar and we will see the difference in details next.

We can also use Pattern and Matcher to replace substring from String like bellow.


Pattern p = Pattern.compile("\\$\\{USERNAME\\}");
Matcher m = p.matcher(ORIGINAL_STRING);
p = Pattern.compile("\\$\\{USERNAME\\}");
m = p.matcher(ORIGINAL_STRING);
m.replaceAll(USERNAME_VALUE);

But the for most of the cases much better and efficient way to replace substring is to use Apache StringUtils Utility Class.

I have created some test methods which utilizes the above mentioned different approch, which can be found in
JavaStringManipulate.Java Class.

The following results clearly shows that the Apache StirngUtils is the best way to replace string followed by StringBuilder

Results from the JavaStringManipulate.Java on  my workstaion[Windows 7,Intel Core I5, and 4GB of Ram]


THIS IS A TEST STRING, WITH A sbhattacahrjee SOME WHERE IN THE STRING TO MAKE LIFE A BIT EASIER HERE IS USERADDRESS
replaceWith_PatternMacher() Took total time = 994
THIS IS A TEST STRING, WITH A sbhattacahrjee SOME WHERE IN THE STRING TO MAKE LIFE A BIT EASIER HERE IS USERADDRESS
replaceWith_StringBuilder() Took total time = 67
THIS IS A TEST STRING, WITH A sbhattacahrjee SOME WHERE IN THE STRING TO MAKE LIFE A BIT EASIER HERE IS USERADDRESS
replaceWith_StringReplace() Took total time = 803
THIS IS A TEST STRING, WITH A ${USERNAME} SOME WHERE IN THE STRING TO MAKE LIFE A BIT EASIER HERE IS USERADDRESS
replaceWith_ApacheStringUtil() Took total time = 53

For the string combination each method was executed 500 times to compare the time taken.



No comments :

Post a Comment