I need to take a string “S” and insert a comma every 3 characters
so convert this
ABCDEFGHIJ
to this
A,BCD,EFG,HIJ
note the groups of 3 count from the RIGHT
I need to take a string “S” and insert a comma every 3 characters
so convert this
ABCDEFGHIJ
to this
A,BCD,EFG,HIJ
note the groups of 3 count from the RIGHT
let reversedString = String(s.reversed())
var result = ""
var counter = 0
for char in reversedString {
if counter > 0 && counter % 3 == 0 { result.append(",")}
result.append(char)
counter += 1
}
s=String(result.reversed())
Your AI code is much better than the ones I generated.
Maybe you could update it so it loop 3 chars at at time so it loops 1/3 less times?
I thought you were inserting commas not colons ?
I am, but I had not yet created the “,” glyph used by the app, so the “:” was for testing
For 8th I would probably write something like:
: 3split-from-right \ s -- s
s:len 3 n:/mod !if
drop
else
s:/ -1 ( [3] s:/ "," a:join ) a:op! "," a:join
then ;
Where’s APL when we need it most?
I’d write it but since APL is a write only language not sure that’d be useful to anyone reading it
Would this be a moderate improvement by eliminating the need to check if counter > 0 each time:
let reversedString = String(s.reversed())
var result = “”
var counter = 1
for char in reversedString {
result.append(char)
if counter % 3 == 0 { result.append(“,”)}
counter += 1
}
s=String(result.reversed())