Kotlin split string to array

Kotlin – Split String – Examples

Kotlin Split String using a given set of delimiters or Regular Expression – Splitting a string to parts by delimiters is useful when the string contains many (parametric) values separated by delimiters or if the string resembles a regular expression. In this tutorial we shall learn how to split a string in Kotlin using a given set of delimiters or Regular Expression.

*Delimiter is a character or another string that joins multiple strings into a single one.

Example 1 – Split String using Single Delimiter

In the following example, we shall split the string Kotlin TutorialsepTutorial KartsepExamples with the Delimiter sep .

[Kotlin Tutorial, Tutorial Kart, Examples]

Example 2 – Split String using Multiple Delimiters

Multiple delimiters could be provided as arguments to the split() method of String Class.

String.split(delimiter1, delimiter2, . delimiterN)

In the following example, we shall split the string Kotlin TutorialsepTutorialasepKartsepExamples with two delimiters sep , asep .

[Kotlin Tutorial, Tutorial, Kart, Examples]

Example 3 – Split String Ignoring Case

split() method accepts a boolean value after delimiters, whether to ignore the case of delimiters and the string while splitting.

Читайте также:  Javascript get all key in object

The default argument for ignoreCase is false. To ignore the case, true has to be provided for the ignoreCase as named argument.

In the following example, we shall split the string Kotlin TutorialsEPTutorialaSEpKartSEpExamples with two delimiters SEP , ASEP .

[Kotlin Tutorial, Tutorial, Kart, Examples]

Example 4 – Split String using Regular Expression

In the following example, we shall split the string Kotlin TutorialsepTutorialasepKartsepExamples with the Regular Expression sep|asep .

[Kotlin Tutorial, Tutorial, Kart, Examples]

Conclusion

In this Kotlin Tutorial – Kotlin Split String, we have learnt to split string using delimiters, ignoring case, and Regular Expression with examples.

  • How to Check if String Ends with Specified Character in Kotlin?
  • How to Check if String Ends with Specified String in Kotlin?
  • How to Check if String Starts with Specified Character in Kotlin?
  • How to Check if String Starts with Specified String Value in Kotlin?
  • How to Check if Two Strings are Equal in Kotlin?
  • How to Compare Strings in Kotlin?
  • How to Compare Strings in Kotlin?
  • How to Create an Empty String in Kotlin?
  • How to Filter Characters of String in Kotlin?
  • How to Filter List of Strings based on Length in Kotlin?
  • How to Filter only Non-Empty Strings of Kotlin List?
  • How to Filter only Strings from a Kotlin List?
  • How to Get Character at Specific Index of String in Kotlin?
  • How to Initialize String in Kotlin?
  • How to Iterate over Each Character in the String in Kotlin?
  • How to Remove First N Characters from String in Kotlin?
  • How to Remove Last N Characters from String in Kotlin?
  • How to check if a String contains Specified String in Kotlin?
  • How to create a Set of Strings in Kotlin?
  • How to define a List of Strings in Kotlin?
  • How to define a String Constant in Kotlin?
  • How to get Substring of a String in Kotlin?
  • Kotlin String Concatenation
  • Kotlin String Length
  • Kotlin String Operations
  • Kotlin String.capitalize() – Capitalize First Character
  • Kotlin – Split String to Lines – String.lines() function
  • Kotlin – String Replace – Examples
  • Kotlin – String to Integer – String.toInt()
  • [Solved] Kotlin Error: Null can not be a value of a non-null type String

Источник

split

Splits this char sequence to a list of strings around occurrences of the specified delimiters.

Parameters

delimiters — One or more strings to be used as delimiters.

ignoreCase — true to ignore character case when matching a delimiter. By default false .

The maximum number of substrings to return. Zero by default means no limit is set.

To avoid ambiguous results when strings in delimiters have characters in common, this method proceeds from the beginning to the end of this string, and matches at each position the first element in delimiters that is equal to a delimiter in this instance at that position.

fun CharSequence . split (
vararg delimiters : Char ,
ignoreCase : Boolean = false ,
limit : Int = 0
) : List < String >
(source)

Splits this char sequence to a list of strings around occurrences of the specified delimiters.

Parameters

delimiters — One or more characters to be used as delimiters.

ignoreCase — true to ignore character case when matching a delimiter. By default false .

limit — The maximum number of substrings to return.

Splits this char sequence to a list of strings around matches of the given regular expression.

Parameters

limit — Non-negative value specifying the maximum number of substrings to return. Zero by default means no limit is set.

Splits this char sequence around matches of the given regular expression.

This function has two notable differences from the method Pattern.split:

  • the function returns the result as a List rather than an Array ;
  • when the limit is not specified or specified as 0, this function doesn’t drop trailing empty strings from the result.

Parameters

limit — Non-negative value specifying the maximum number of substrings to return. Zero by default means no limit is set.

Источник

Split a String Into an Array in Kotlin

Split a String Into an Array in Kotlin

  1. Create a Kotlin Project
  2. Read Text From a File in Kotlin
  3. Use the split() Method and the Array() Constructor to Split a String Into an Array in Kotlin
  4. Use the split() and toTypedArray() Methods to Split a String Into an Array in Kotlin
  5. Remove Leading and Trailing Whitespaces After Splitting a String Into an Array in Kotlin
  6. Conclusion

A series of character sequences always form a string, and we can retrieve each of the character sequences when there is a need to do so. For example, in a real-world application, users usually use a sequence of characters to search for a particular service or product in the application.

We do not usually use the entire sequence of characters to perform a search. We typically retrieve keywords from the search term and use them to perform the search.

This tutorial will show how to split a string into an array of strings in Kotlin. You can use this technique to search in an application, as mentioned above, by retrieving the keywords from the string array.

Create a Kotlin Project

Open IntelliJ IDEA and select File > New > Project . On the window that opens, enter the project name as split-string , select Kotlin in the Language section, and select IntelliJ in the Build System section.

Finally, press the Create button to generate the project.

Once the project is generated, create a file named data.txt under the src folder and paste this text into the file.

Your, service, provider, is, wishing, you, a, good, day 

This text contains a single line of a string, with each string separated from the other using a comma. We will use this file to read the string into our application.

Read Text From a File in Kotlin

Create a second file named Main.kt under the src/main/kotlin folder and copy and paste the following code into the file.

import java.io.File  private val fileData = File("src/data.txt");  fun readFileData(): String   return fileData.bufferedReader()  .readLine(); >  fun main()  println(readFileData()); > 

In this code, we have created a method named readFileData() that uses a BufferedReader to read the line we added in the data.txt file using the readLine() method.

The BufferedReader provides an efficient way of reading data from a file because the data is read into a buffer instead of reading it directly from the file. If we need this data again, the data will be obtained from the buffer.

The readLine() method reads a single text line if one exists; else, the method returns null. The end of a line is identified by a line feed \n , a carriage return \r , or EOF , which means the end of the file.

Run this code and note that our file is read successfully. The contents will be logged to the console, as shown below.

Your, service, provider, is, wishing, you, a, good, day 

Use the split() Method and the Array() Constructor to Split a String Into an Array in Kotlin

Comment on the main() method in the previous example and copy and paste the following code into the Main.kt file after the readFileData() method.

fun usingSplitAndArray(): Array   val stringData: List = readFileData()  .split(",");   return Array(stringData.size) < index ->  stringData[index]  >  >  fun main()  println(usingSplitAndArray()[0]) > 

In this code, we have created a method named usingSplitAndArray() that calls the split() method on the string returned by the readFileData() method to return a list of string List values.

The split() method uses commas as delimiters for the string. Note that you can pass a variable number of delimiters in the split() method to achieve the desired result.

Since we wish to return an array of strings Array , we use the list returned to create a new Array using the Array() constructor. This constructor accepts two arguments: the first being the array size and the second being a lambda expression that accepts an int and returns a type T .

Since our list can provide all these arguments, we pass the list size as the first argument of the Array() constructor, and the second argument uses the index of each item in the list to return the array’s values.

To verify that our string was converted to an array, we have logged the value at index 0 from the returned array usingSplitAndArray()[0] in the main() method.

Run this code and ensure the output is as shown below.

Use the split() and toTypedArray() Methods to Split a String Into an Array in Kotlin

Comment out the main() method in the previous example and copy and paste the following code into the Main.kt file after the usingSplitAndArray() method.

fun usingToTypedArray(): Array   return readFileData()  .split(",")  .toTypedArray(); >  fun main()  println(usingToTypedArray()[1]) > 

In this code, we created a function named usingToTypedArray() that returns an array of strings Array from the list returned by the split() method.

In the previous example, we mentioned that the split() method returns a list of strings List , and we can use the Array() constructor to create an array of strings.

This example is much easier than the previous example as we only need to call the toTypedArray() method on the returned list to return a typed array which is simply an array of strings Array .

In the main() method, we logged the value at index 1 returned by the array to verify that the string was converted to an array.

Run this code and ensure the output is as shown below.

Remove Leading and Trailing Whitespaces After Splitting a String Into an Array in Kotlin

Comment out the main() method in the previous example and copy and paste the following code into the Main.kt file after the usingToTypedArray() method.

fun usingTrimMethod(): Array   return readFileData()  .split(",")  .map(String::trim)  .toTypedArray() >  fun main()  println(usingTrimMethod()[1])  > 

Note that our text contains leading whitespaces and the previous example returned a value with the whitespace as part of the string. To remove the leading and trailing whitespaces, we invoke the map() method and pass the trim() method as its argument.

The trim() method is a transform function that removes all the leading and trailing whitespaces if any exist. This example is similar to the previous one, and its main objective is to show how to eliminate whitespaces.

Run this example and note that the value logged to the console, in this case, does not have whitespace, as shown below.

Conclusion

  1. Reading a line of string from a text file.
  2. Using the split() method and the Array() constructor to return an array of strings.
  3. Using the split() method and toTypedArray() method to return an array of strings.

David is a back end developer with a major in computer science. He loves to solve problems using technology, learning new things, and making new friends. David is currently a technical writer who enjoys making hard concepts easier for other developers to understand and his work has been published on multiple sites.

Related Article — Kotlin String

Источник

Оцените статью