Is there a more elegant way to convert a string to an array?

I would like to convert a 11-digit string to 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 was 12345 , then the array will look like string[1] = 1; string[2] = 2 string[1] = 1; string[2] = 2 etc.

+4
source share
4 answers

There is an elegant way that I think will work in any version of ColdFusion.

The trick is to use CF list management functions - if you specify the separator "" (i.e. nothing), it will see each character of the string as an element of the list.

So you want:

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

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

+7
source

This works on CF8 and does not rely on a β€œbug” in CF9:

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

If you really want to use the Java method String.split (), it returns String [], so you have to copy its values ​​into a new array, for example. myArray = arrayNew(1) + myArray.addAll( myStringArr ) .

0
source

Interestingly, 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 basic java methods and classes. According to Rupesh Kuman from Adobe (http://coldfused.blogspot.com/2007/01/extend-cf-native-objects-harnessing.html), the CF array is an implementation of java.util.List, so all lists are also available for CF arrays. One of the most useful 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 the list as an 11-digit number, use the split method to create an array, and then display 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 will see that you end up with an array of 12 elements, with the first index element empty. Just delete it with ArrayDelete () or ArrayDeleteAt () and you should be good to go. This should work with all versions of ColdFusion with CFMX 6.

-2
source

All Articles