Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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.

for (i, c) in s.chars().enumerate() {
    println!("Char {} is {}", i, c);
}
(dorun (map-indexed (fn [i c] (println "Char" i "is" c)) s))
s.split('').asMap().forEach((i, c) => print('Char $i is $c'));
use iso_fortran_env
  integer, parameter :: ucs4  = selected_char_kind ('ISO_10646')
  character(kind=ucs4,  len=30) :: s
open (output_unit, encoding='UTF-8')

do i=1,len(s)
  print *,"Char ", i, " is ", s(i:i)
end do
i := 0
for _, c := range s {
	fmt.Printf("Char %d is %c\n", i, c)
	i++
}
forM_ (zip [0 ..] s) (\(i, c) -> putStrLn $ "Char " ++ show i ++ " is " ++ [c])
for (const [i, c] of [...s].entries()) {
	console.log(`Char ${i} is ${c}`);
}
import static java.lang.System.out;
record E(int c) {
    static int z;
    E { out.printf("Char %s is %c%n", z++, c); }
}
s.chars().forEach(E::new);
import static java.util.stream.IntStream.range;
range(0, s.length())
    .forEach(i -> {
        out.printf("Char %s is %s%n", i, s.charAt(i));
    });
import java.util.concurrent.atomic.AtomicInteger;
AtomicInteger i = new AtomicInteger(0);
s.chars().forEach(v -> {
  char c = (char)v;
  System.out.println("Char " + i.getAndIncrement() + " is " + c); 
});
for(int i=0; i<s.length(); i++) {
  char c = s.charAt(i);
  System.out.println("Char " + i + " is " + c); 
}
s.forEachIndexed { i, c ->
  println("Char $i is $c")
}
lazutf8
for i := 1 to utf8length(s) do
  writeln(format('Char %d is %s',[i, utf8copy(s,i,1)]));
use v5.10;
use utf8;
binmode STDOUT, ":utf8"; 

while ($s =~ /(\X)/g) {
    say 'Char ' . pos($s) . ' is ' . $1;
}
for i, c in enumerate(s):
    print(f'Char {i} is {c}')
f = lambda i, c: f'Char {i} is {c}'
for e in enumerate(s): print(f(*e))
s.each_char.with_index{|c, i| puts "Char #{i} is #{c}" }

New implementation...