Just thought I’d write up a quick post on converting a string of characters to an array of characters. I’ve never had any difficulty doing this using Java’s getBytes() method which converts a given string to an array of it’s equivalent byte code. Nonetheless I just stumbled upon a native Coldfusion method that does the same exact thing without having to directly access the underlying Java.
To convert a string to an array of character bytes using Coldfusion simply use the charsetdecode() method. You can then loop over the byte array and encode each character using the chr() method, and set into a new array. In the end you will end up with an array of the characters including white spaces and all. Also any string you pass through the charsetdecode() method you can pass back through the charsetencode() method to convert it back into its original string. A quick example of this is below.
<!--- SET A STRING ---> <cfset VARIABLES.myname = "My name is Matthew."> <!--- CONVERT TO AN ARRAY OF BYTES ---> <cfset VARIABLES.bytes = charsetdecode(VARIABLES.myname, "us-ascii")> <!--- CREATE AN EMPTY ARRAY ---> <cfset VARIABLES.data = arrayNew(1)> <!--- LOOP OVER ARRAY OF BYTE CODE ---> <cfloop array="#VARIABLES.bytes#" index="VARIABLES.i"> <!--- SET EACH CHARACTER INTO THE ARRAY ---> <cfset arrayAppend(VARIABLES.data, chr(VARIABLES.i))> </cfloop> <!--- DUMP THE ARRAY ---> <cfdump var="#VARIABLES.data#">
It outputs the following.
It can now be treated as any array. What else have I been overlooking?
Just curious…what’s wrong with dropping to Java and doing VARIABLES.myname.toCharArray()?
Seems much easier then messing with all that other code… just wondering if maybe there’s a reason you wanted to avoid using Java.
Your definitely right, it is a lot of extra markup. While I have a few go-to Java functions I am tremendously more comfortable working with coldfusion. In this case though it would probably be wise to stick with the java function, although if all you’re trying to do is set the string to an array of bytes, using charsetdecode() seems, for me at least, as simple as using java’s getBytes(). I should really spend more time looking into java.