Mohamad
Mohamad

Reputation: 35349

Is there a more elegant way to transform a string into an array?

I would like to convert a string of 11 digits into an array. Is there a more elegant way to do this in ColdFusion 9?

local.string = [];

for (local.i = 1; local.i <= len(arguments.string); local.i++)
{
    local.string[ local.i ] = mid(arguments.string, local.i, 1);
}

If my string were 12345, then the array would look like string[1] = 1; string[2] = 2, etc...

Upvotes: 4

Views: 3709

Answers (4)

Mike Causer
Mike Causer

Reputation: 8324

If you really want to use the java method String.split(), it returns a String[], so you'll have to copy it's values into a new array eg. myArray = arrayNew(1) + myArray.addAll( myStringArr ).

Upvotes: 0

Larry C. Lyons
Larry C. Lyons

Reputation: 403

Interesting, it appears that you can do something similar using the .split() java method and get similar results.

A bit of background: since CF is built on Java, it can take advantage of many of the underlying java methods and classes. According to Rupesh Kuman of Adobe (http://coldfused.blogspot.com/2007/01/extend-cf-native-objects-harnessing.html), a CF array is an implementation of java.util.List, so all the list methods are also available for CF arrays. One of the more useful ones is the .split() method. This takes a string and turns it into an array based on an arbitrary delimiter of 0 or more characters.

Here's what I did: set a list to be an 11 digit number, used the split method to create the array and then displayed the result.

    <cfset testList = "12345678901" />
    <cfset testArray = testList.split("") />
    <cfset request.cfdumpinited = false />
    <cfdump label="testArray" expand="true" var="#testArray#"/>
    <cfabort />

If you run this, you see that you end up with a 12 item array with the first index item being empty. Just delete that one using ArrayDelete() or ArrayDeleteAt() and you should be good to go. This should work with all versions of ColdFusion since CFMX 6.

Upvotes: -2

CfSimplicity
CfSimplicity

Reputation: 2363

This works on CF8 and doesn't rely on the "bug" in CF9:

stringAsList = REReplace( string,"(.)","\1,","ALL" );
array = ListToArray( stringAsList );

Upvotes: 6

sebduggan
sebduggan

Reputation: 561

There's an elegant way which I think will work in any version of ColdFusion.

The trick is to use CF's list manipulation functions - if you specify a delimiter of "" (i.e. nothing) it will see each character of the string as a list item.

So what you want is:

local.string = listToArray(arguments.string, "");

And that will give you your array of characters...

Upvotes: 8

Related Questions