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.

2 comments:

  1. 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 ;-)

    ReplyDelete
  2. 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.

    ReplyDelete

Note: Only a member of this blog may post a comment.