Menu
Coddy logo textTech

Iterating Over Strings P1

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 76 of 93.

Just like lists, strings can be iterated character by character using a for loop. In Kotlin, a string is essentially a sequence of characters, so the same iteration pattern applies.

val word = "Hello"
for (char in word) {
    println(char)
}
// Output:
// H
// e
// l
// l
// o

Each iteration gives you a single Char from the string. This is useful when you need to examine or process each character individually, such as counting specific letters or building a new string based on certain conditions.

val text = "Kotlin"
var count = 0
for (char in text) {
    if (char == 'o' || char == 'i') {
        count++
    }
}
println(count)  // 2

You can also use withIndex() on strings to get both the position and the character, just like with lists:

val name = "Ada"
for ((index, char) in name.withIndex()) {
    println("$index: $char")
}
// Output:
// 0: A
// 1: d
// 2: a
challenge icon

Challenge

Medium

Read a string from input and count how many vowels (a, e, i, o, u) it contains. Consider both lowercase and uppercase vowels.

Iterate through each character in the string and check if it's a vowel. Print the total count of vowels found.

Input format:

  • A single string

Output format:

Print a single integer representing the number of vowels in the string.

Hint: You can convert each character to lowercase using lowercaseChar() before checking, or check for both cases separately.

Try it yourself

fun main() {
    // Read input
    val text = readLine()!!
    
    // TODO: Write your code below to count the vowels in the string
    
    
    // Output the result
    println(count)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground