Replace every nth character in a character vector with a comma

97 Views Asked by At

For example if n=5, I want this:

names:("Saint Denis";"Rhodes";"Strawberry";"Valentine";"Omar")

to become this

"Sain, Den,s" "Rhod,s" "Stra,berr," "Vale,tine" "Omar"

I believe I have to use ssr and iterate through my list, so something like this

{$[count x < 4;x;ssr[x;"????.";","]]} each names

Any Ideas?

2

There are 2 best solutions below

0
Maurice Lim On

You can do something like this:

q){[x;n]@[x;-1+n*1+til count[x]div n;:;","]}[;5]each names
"Sain, Den,s"
"Rhod,s"
"Stra,berr,"
"Vale,tine"
"Omar"

Explanation:

q)x
"Saint Denis"
q)count[x]div 5 / Returns the greatest whole number that does not exceed x%y
2
q)-1+5*1+til count[x]div 5 / Get the indices to replace
4 9
q)@[x;-1+5*1+til count[x]div 5;:;","] / Ammend at indices
"Sain, Den,s"
0
terrylynch On

Another approach using fill

q){x^count[x]#"    ,"}'[names]
"Sain, Den,s"
"Rhod,s"
"Stra,berr,"
"Vale,tine"
"Omar"