Iterating Over Strings P2
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 77 of 93.
Beyond basic iteration, strings offer several useful methods for building new strings from existing ones. A common task is transforming characters while iterating and collecting the results.
You can build a new string by appending characters to a StringBuilder or simply concatenating to a string variable:
val original = "hello"
var result = ""
for (char in original) {
result += char.uppercaseChar()
}
println(result) // HELLOThe uppercaseChar() method converts a single character to uppercase, while lowercaseChar() does the opposite. These work on individual Char values, unlike uppercase() which works on entire strings.
Another practical technique is filtering characters while iterating. For example, extracting only digits from a mixed string:
val mixed = "a1b2c3"
var digits = ""
for (char in mixed) {
if (char.isDigit()) {
digits += char
}
}
println(digits) // 123Kotlin provides helpful character-checking methods like isDigit(), isLetter(), and isWhitespace() that return true or false based on the character type. These make it easy to filter or categorize characters during iteration.
Challenge
MediumWrite a function extractLetters that takes a text string and returns a new string containing only the letters, converted to uppercase.
Iterate through each character, filter out non-letters, and convert the remaining characters to uppercase.
Parameters:
text(String): A string that may contain letters, digits, spaces, and special characters
Returns: A string containing only the letters from the input, all converted to uppercase (String)
Try it yourself
fun extractLetters(text: String): String {
// Write code here
}
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