4 minutes read

In some sense, a string looks like a list of characters. You can iterate both over strings and lists. However, sometimes you need to turn a string into a list.

Splitting the string

A string can be separated by delimiters to a list of strings. To perform this, call the method split() , it divides a string into substrings by a separator. In the previous example, we used the " " delimiter, which splits a string into separate words by spaces. Notably, the delimiter itself is not included in any of the substrings.

The method returns a List of all the substrings. The List is similar to MutableList, but you cannot reassign elements in the List and you cannot resize the List. You can easily convert List to MutableList and vice versa with toMutableList() and toList() functions.

val sentence = "a long text"
val wordsList: List<String> = sentence.split(" ") // ["a", "long", "text"]

val mutableWordList = sentence.split(" ").toMutableList() // MutableList ["a", "long", "text"]

Let's try to split an American phone number into country code, area code, central office code, and other remaining digits:

val number = "+1-213-345-6789"
val parts = number.split("-") // ["+1", "213", "345", "6789"]

Note that all the parts are still strings no matter how they look!

Choose your delimiter wisely, otherwise, you can receive some sentences that start with a space:

val text = "That's one small step for a man, one giant leap for mankind."
val parts = text.split(",") // ["That's one small step for a man", " one giant leap for mankind."]

You can choose any delimiter you prefer, even the combination of spaces and words:

val text = "I'm gonna be a programmer"
val parts = text.split(" gonna be ") // ["I'm", "a programmer"]

As you can see, the split method is also a good tool to get rid of something you don't need or don't want to use.

Iterating over a string

It's possible to iterate over characters of a string using a loop.

See the following example of iterating with range indices.

val scientistName = "Isaac Newton"

for (i in 0 until scientistName.length) {
    print("${scientistName[i]} ") // print the current character
}

The code outputs:

I s a a c   N e w t o n 

Also, you can iterate through a string:

val str = "strings are not primitive types!"

var count = 0
for (ch in str) {
    if (Character.isWhitespace(ch))
        count++
}

println(count) // 4

The code above counts and prints the number of spaces in str. The result is 4.

Example of iterating through an array by indices:

val rainbow = "ROYGCBV"

for (index in rainbow.indices){
    println("${index+1}: ${rainbow[index]}")
}

The code above prints the colors of the rainbow with their numbers. The output is:

1: R
2: O
3: Y
4: G
5: C
6: B
7: V

While the previous examples showcase direct iteration over strings, you can also convert a string to a character array using toCharArray() and then iterate over that array. This can be useful if you need to modify the characters during iteration:

val message: String = "Hello, world!"
val charArray: CharArray = message.toCharArray()

for (i in charArray.indices) {
    if (charArray[i] == 'o') {
        charArray[i] = 'O' // Replace lowercase 'o' with uppercase 'O'
    }
}

println(String(charArray)) // Output: HellO, wOrld!

In this example, we convert message to charArray, iterate over it, and replace lowercase 'o's with uppercase 'O's. Finally, we create a new string from the modified charArray. This demonstrates how toCharArray() provides mutability when iterating over characters, allowing you to manipulate the individual characters within the string representation.

Conclusion

In this section, we have discussed simple ways to handle strings. It may sound simple, but this knowledge can help you solve even non-trivial problems. Good luck with your tasks!

573 learners liked this piece of theory. 8 didn't like it. What about you?
Report a typo