Pandu
Pandu

Reputation: 1686

How can I do something like "for char in string" in Vim script?

I've come up with this, but is there simple way I'm missing?

for s:char in split(s:string, '.\zs\ze.')

Upvotes: 12

Views: 2204

Answers (2)

smemsh
smemsh

Reputation: 114

In vim >= 8.2.2658 (74e54fcb44), a string can be used in a vim for loop to use each character in turn:

 $ vim -u NONE -E \
   -c 'redir! >/dev/stdout' \
   -c 'for i in "abc" | echo i | endfor' \
   -c quit \
   </dev/null
a
b
c

Documentation was released in 9.0.0336 (9b03d3e75), in :help :for

When {object} is a |String| each item is a string with one character, plus any combining characters.

Upvotes: 0

Ingo Karkat
Ingo Karkat

Reputation: 172520

The canonical way is

for s:item in split(s:mylist, '\zs')

Upvotes: 18

Related Questions