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?