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
// oEach 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) // 2You 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: aChallenge
MediumRead 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)
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function13Iterating Over Sequences
Iterating Over ElementsWithIndex MethodIterating Over Strings P1Iterating Over Strings P2Recap - Indexed Letters2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground