I have to loop over a string to evaluate each character in the string
and determine whether each character is numeric. In converting the string
to an array, I came across some odd behavior:
When I use toCharArray() and then use a for loop over the array,
isNumeric() returns false for each value. But if I use a from-to loop and
call the array item by index, it evaluates properly:
strAccountNumber = “8B345-7890”;
arrAccountNumberTCA = strAccountNumber.toCharArray();
dump(var=arrAccountNumberTCA, label=“strAccountNumber.toCharArray()”);
echo(“
”);
for (itmTCA in arrAccountNumberTCA){
echo(“isNumeric(#itmTCA#):” & isNumeric(itmTCA) & " (#itmTCA#)
" );
}
echo(“
echo(“
”);
intTCALen = Len(arrAccountNumberTCA);
loop index=“i” from=“1” to=“#intTCALen#” {
echo(“isNumeric(arrAccountNumberTCA[#i#]): " & isNumeric(
arrAccountNumberTCA[i]) & " (#arrAccountNumberTCA[i]#)
” );
}
echo(“
Oddly, if I use listToArray(“”) instead, neither the for loop nor the
from-to loops return the expected values from isNumeric():
strAccountNumber = “8B345-7890”;
arrAccountNumberLTA = strAccountNumber.listToArray(“”);
dump(var=arrAccountNumberLTA, label=“strAccountNumber.listToArray(”“”“)”);
echo(“
”);
for (itmLTA in arrAccountNumberLTA){
echo(“isNumeric(#itmLTA#):” & isNumeric(itmLTA) & " (#itmLTA#)
" );
}
echo(“
echo(“
”);
intLTALen = Len(arrAccountNumberLTA);
loop index=“i” from=“1” to=“#intLTALen#” {
echo(“isNumeric(arrAccountNumberLTA[#i#]): " & isNumeric(
arrAccountNumberLTA[i]) & " (#arrAccountNumberLTA[i]#)
” );
}
echo(“
Is this a bug, expected behavior, or am I going about this the wrong way?
I guess I could just use Mid without converting the string to an array:
strAccountNumber = “8B345-7890”;
echo(“
”);
intStrLen = Len(strAccountNumber);
loop index=“i” from=“1” to=“#intStrLen#” {
echo(“isNumeric(Mid(strAccountNumber, #i#, 1)): " & isNumeric(Mid(
strAccountNumber, i, 1)) & " (#Mid(strAccountNumber, i, 1)#)
” );
}
echo(“
Is there a “best” way to do this?
Environment is:
Version Lucee 4.5.3.018 final
OS Mac OS X (10.11.6) 64bit
Remote IP 127.0.0.1
Servlet Container Apache Tomcat/8.0.15
Java 1.8.0_66 (Oracle Corporation) 64bit
Architecture 64bit
Thanks,
Juan