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:
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:
Using String Templates:
Using Collection Operations:
Kotlin provides powerful collection operations like joinToString. Here’s how:
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:
In this example, trim is used to remove leading and trailing whitespaces from a string.
