MAKE STRINGS EASIER: REPLACE THEM Java strings are not the easiest things to work with in Java code. Their C roots show and developers are often left with a wish for the power of a language like Perl. But the drawbacks of Java strings can be easily solved by creating static "functions" that perform common tasks upon strings. One such common function is the ability to replace a substring within a string with another substring. For example, replace "high" with "zoo" in "highlander" and replace "$foo" with "green" in "Favorite Color: $foo". The replacement code statement is relatively simple but not something that a development team will want to repeat again and again. For example: /** * Replace a string with another string inside a larger string. * * @param text String to do search and replace in * @param repl String to search for * @param with String to replace with * * @return String with all values replaced */ static public String replace (String text, String repl, String with) { int idx = 0; while( (idx = text.indexOf(repl)) != -1) { text = text.substring(0,idx) + with + text.substring(idx+repl.length() ); idx += with.length(); // jump beyond replacement } return text; } Using our replace method, the code looks like: String example1 = replace ("highlander", "high", "zoo"); // output "zoolander" String example2 = replace ("Favorite Color: $foo", "$foo", "green"); // output "Favorite Color: green" As time goes by, the standard replace method should be refactored to increase its genericity. One such improvement is to allow the number of times the value should be replaced to be specified. For example: String example3 = replace ("a high highlander high in the highlands", "high", "low", 2); // output "a low lowlander high in the highlands" Other improvements might allow a range of specified substitutions: // start at 2, stop at 3 String example4 = replace ("a high highlander high in the highlands", "high", "low", 2, 3); // output "a high lowlander high in the highlands" or the optimization of the replacement method. Rather than using the simple method above, char[] could be used to garner faster speeds for larger strings. Also, a stringbuffer could be used to store the currently changed text rather than to keep changing the original string. Once an API interface is defined, these optimizations can happen without needing change on the part of the code that calls them. Having a well-thought-out and well-crafted set of common "functions" allows a development team to improve productivity and concentrate on improving the speed of the standard code. ----------------------------------------