Over the weekend, I was reading through the Learn Modern ColdFusion <CFML> in 100 Minutes book by Ortus Solutions when I came across their section on Character Extraction. In that section, they mention that - in Lucee CFML - you can access the characters of a String using Array-notation. Since I don't remember ever seeing this feature before, I wanted to quickly try it out for myself so as to try and burn the concept into my brain.
Like all ColdFusion arrays, lists, queries, etc, treating a String like an array of characters starts at index 1:
<cfscript> value = "Jello"; // A string can be accessed like an array of characters (1-based, of course). echo( value[ 1 ] & "-" ); echo( value[ 2 ] & "-" ); echo( value[ 3 ] & "-" ); echo( value[ 4 ] & "-" ); echo( value[ 5 ] & "-" ); // Going out-of-bounds will throw an error; but, we can use our Elvis-operator to // provide a fall-back value for a null index. echo( value[ 6 ] ?: "!" ); </cfscript>
As you can see, we are treating String
value as a character Array. And, when we run this Lucee CFML code, we get the following output:
Interesting! To be honest, I don't have a lot of use-cases in which I have to iterate over the characters in a string in ColdFusion. But, it's good to know that this feature exists should the need arise.
ASIDE: I tried to use negative array indexing, like
value[ -1 ], to grab the last character in the string. This does not work.
Also, attempting to use
.map()on the String does not throw an error; but, it does not iterate over the string characters. It appears to perform a single iteration with the String value as the one iteration item.
value[ Len(value) ]
I presume this works, for referencing the last character in
So, essentially, a string is an array of chars?
Yes, that's exactly right. But here's my emotional struggle: by the
time you are going to start pulling in other methods like
len(), I would probably just revert back to a simpler:
value.right( 1 ). That's why I think this is
"interesting"; but, I'm not sure how often I would actually