How to split a string into an array of substrings in Kotlin
How to split a string into an array of substrings in Kotlin.
Here's a step-by-step tutorial on how to split a string into an array of substrings in Kotlin:
Start by creating a string that you want to split. For example, let's say we have the following string:
val sentence = "Hello, world! How are you?"To split the string, you can use the
split()function, which is available in the Kotlin standard library. Thesplit()function takes a delimiter as an argument and returns an array of substrings. In our case, we want to split the string at every space, so we can use a space as the delimiter. Here's how you can split the string:val words = sentence.split(" ")In this example, the
split()function will split the string at every space character and return an array of substrings.You can also split the string using a regular expression as the delimiter. For example, if you want to split the string at every occurrence of a comma or a space, you can use the following code:
val words = sentence.split("[,\\s]".toRegex())In this case, the
split()function will split the string at every comma or space character and return an array of substrings.By default, the
split()function removes any leading or trailing empty strings from the resulting array. However, if you want to include empty strings in the array, you can pass a second argument to thesplit()function. This argument specifies the maximum number of substrings to return. Here's an example:val words = sentence.split(" ", 3)In this case, the
split()function will split the string at every space character, but it will return at most 3 substrings. If there are more than 3 substrings, the remaining substrings will be included as a single string in the last element of the resulting array.After splitting the string, you can access the individual substrings in the resulting array using the indexing operator. For example, to print each word in the array, you can use a loop:
for (word in words) {
println(word)
}This code will iterate over each element in the
wordsarray and print it to the console.
That's it! You now know how to split a string into an array of substrings in Kotlin.