Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 644
Mohamad Avatar asked Dec 22 '22 14:12

Mohamad


2 Answers

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

like image 94
sebduggan Avatar answered Dec 24 '22 02:12

sebduggan


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

stringAsList = REReplace( string,"(.)","\1,","ALL" );
array = ListToArray( stringAsList );
like image 24
CfSimplicity Avatar answered Dec 24 '22 04:12

CfSimplicity