SyntaxHighlighter

Thursday, July 28, 2011

join and split

You can join elements in a List to form one String, and you can take a String and split it and put them into a List.


def langs = ['haskell', 'python', 'groovy', 'java', 'php', 'c']
println langs.join(' > ') // my interest level at the moment.
def scripts = "JavaScript, coffeeScript, clojureScript"
// notice again that there's no trailing colon ":" in below. Yay!
println scripts.split(',').collect { it.trim() }.join(":")


For some this is trivial, for others, not-so-trivial.
When I first encountered join() and split() in perl during my uni days, I thought this toy-like function wouldn't be really useful in real world applications. How wrong I was.
I'm not sure why this functionality never made into JDK still. Apache Common Lang's StringUtils is helpful here, but not when that function is the only thing I needed. I mean, am I the only one who wrote something like the following over and over again?


StringBuffer sb = "";
for (String s : list) {
sb.append(s).append(":");
}
String result = sb.toString().substring(0, sb.length() - 1);

No comments:

Post a Comment