Logo

Programming-Idioms

  • Go
  • Pascal

Idiom #286 Iterate over characters of a string

Print a line "Char i is c" for each character c of the string s, where i is the character index of c in s (not the byte index).

Make sure that multi-byte characters are properly handled, and count for a single character.

lazutf8
for i := 1 to utf8length(s) do
  writeln(format('Char %d is %s',[i, utf8copy(s,i,1)]));
i := 0
for _, c := range s {
	fmt.Printf("Char %d is %c\n", i, c)
	i++
}

c is a rune.
s is assumed encoded in UTF-8.

This first range variable is ignored, as it provides positions in bytes, instead of runes count.
(dorun (map-indexed (fn [i c] (println "Char" i "is" c)) s))

In Clojure a string is a list of characters

New implementation...