Wednesday, June 21, 2006

A Better Way to Make a String Array

I was jumping through some hoops to generate a true Java String array in CFML yesterday to pass in to a web service API. Today, while talking to some of the guys on the CF team it came up that there is a really simple way to get an array of Strings in CFML: Use the Java String split() API!

Code before:
string = CreateObject("java", "java.lang.String");
array = CreateObject("java", "java.lang.reflect.Array");
cookies = array.newInstance(string.getClass(), 3);
array.set(cookies, 0, "x=1");
array.set(cookies, 1, "x=2");
array.set(cookies, 2, "x=3");

Code After:
s = "x=1,x=2,x=3";
cookies = s.split(",");
I would say the second way is much easier. It is using a regular expression, so it isn't going to go as fast as the first code sample, but for something like this I would not worry about it at all.

3 comments:

PaulH said...

wow that's weird. i was doing some regex a couple of days ago & fell on to split as a way to grab all of a string's alphabet delimited numerics though i was using the regex Pattern class. works like butter ;-)

Rick O said...

Every Application.cfm I've written in the past few years has included:

Request.EvenOdd=ListToArray("even,odd")

And almost every page I've written has:

class="#Reqest.EvenOdd[IncrementValue(CurrentRow MOD 2)]#"

Now, if I just had a function to go from "a=1,b=2,c=3" directly to a Structure with a single (built-in) function call, I'd be a very happy man.

airshoes said...

wow that's weird. i was doing some regex a couple of days ago & fell on to split as a way to grab all of a string's alphabet delimited numerics though i was using the regex Pattern class. works like butter ;-)I like your blog. Thank you. They are really great .
Some new style Puma Cat shoes is in fashion this year.
The Nike Air Shoes is a best Air Shoes .
Nike Air Rift is good and Cheap Nike Shoes.
If you are a fans of Puma basket,we would offer the good and Cheap Puma Shoes for you .the cheap ugg bootsis best christmas gift now.
The information age is really convenient .