Lesson 5
Basic String Manipulation in Kotlin
Lesson Overview

Welcome! In this lesson, we'll delve into the basic string manipulation features of Kotlin, which include string tokenization, string concatenation, trimming of whitespace from strings, and type conversion operations. Kotlin offers concise and expressive syntax for these operations, making your code more readable and efficient.

Tokenizing a String in Kotlin

In Kotlin, we can use the split method from the String class or utilize regular expressions to tokenize a string, effectively splitting it into smaller parts or 'tokens'.

Using split method:

Kotlin
1fun main() { 2 val sentence = "Kotlin is an amazing language!" 3 val tokens = sentence.split(" ") 4 5 for (token in tokens) { 6 println(token) 7 } 8}

In the example above, we use a space as a delimiter to split the sentence into words. This operation will print each word in the sentence on a new line.

Exploring String Concatenation

In Kotlin, string concatenation can be achieved using the + operator, string templates, or collection operations like joinToString, each providing a unique way to combine strings into a larger string:

Using the + Operator:

Kotlin
1fun main() { 2 val str1 = "Hello," 3 val str2 = " World!" 4 val greeting = str1 + str2 5 println(greeting) // Output: "Hello, World!" 6}

Using String Templates:

Kotlin
1fun main() { 2 val str1 = "Hello," 3 val str2 = " World!" 4 val greeting = "$str1$str2" 5 println(greeting) // Output: "Hello, World!" 6}

Using Collection Operations:

Kotlin provides powerful collection operations like joinToString. Here’s how:

Kotlin
1fun main() { 2 val strings = listOf("Hello", "World!", "Kotlin", "Collections!") 3 val result = strings.joinToString(separator = " ") 4 println(result) // Output: "Hello World! Kotlin Collections!" 5}

In this example, we use joinToString to concatenate all elements of the list into a single string with a space separator.

Trimming Whitespaces from Strings

In Kotlin, the trim method can remove both leading and trailing whitespaces from a string:

Kotlin
1fun main() { 2 var str = " Hello, World! " // string with leading and trailing spaces 3 str = str.trim() // remove leading and trailing spaces 4 println(str) // Output: "Hello, World!" 5}

In this example, trim is used to remove leading and trailing whitespaces from a string.

Kotlin Type Conversions

In Kotlin, we can convert strings to numbers using methods like toInt (string to integer) and toFloat (string to float), and other data types to strings using simple string templates:

Kotlin
1fun main() { 2 val numStr = "123" 3 val num = numStr.toInt() 4 println(num) // Output: 123 5 6 val floatStr = "3.14" 7 val pi = floatStr.toFloat() 8 println(pi) // Output: 3.14 9 10 val age = 20 11 val ageStr = age.toString() 12 println("I am $ageStr years old.") // Output: I am 20 years old. 13}

Note: If you try to convert an invalid number (like "abc") using toInt() or toFloat(), it will throw a NumberFormatException. You could handle this using try-catch for a safer conversion.

Integrating String Tokenization and Type Conversions

In some cases, we may need to combine all the methods discussed:

Kotlin
1fun main() { 2 val numbers = "1,2,3,4,6" 3 val numArray = numbers.split(",") 4 var sum = 0 5 6 for (numStr in numArray) { 7 sum += numStr.toInt() 8 } 9 10 val average = sum.toFloat() / numArray.size 11 println("The average is $average") // Output: The average is 3.2 12}

By integrating these methods, we can transform the string "1,2,3,4,6" into a list of integers, calculate their average, and display the result.

Quick Recap and Next Steps

Great job! You've gained an overview of Kotlin's string manipulation features, including string concatenation, string tokenization, trimming whitespace from strings, and type conversions. Now, it's time to get hands-on with these concepts in the exercises that follow. Keep experimenting with Kotlin features, and happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.