🔁 Iteration

Iterating Strings

Walking a string character by character

Strings are iterable in most languages — but Unicode and encoding behave differently.

Language:
Python
Loading...

All languages — Walk characters

JavaScript
const s = "hello";

for (const c of s) {
  console.log(c);
}

// Mit Index:
for (let i = 0; i < s.length; i++) {
  console.log(i, s[i]);
}
TypeScript
const s: string = "hello";

for (const c of s) {
  console.log(c);
}
Java
String s = "hello";

for (char c : s.toCharArray()) {
    System.out.println(c);
}

// Mit Index:
for (int i = 0; i < s.length(); i++) {
    System.out.println(i + " " + s.charAt(i));
}
Go
s := "hello"

for i, c := range s {
    fmt.Printf("%d: %c
", i, c)
}
C++
string s = "hello";

for (char c : s) {
    cout << c << endl;
}

// Mit Index:
for (int i = 0; i < s.size(); i++) {
    cout << i << " " << s[i] << endl;
}