Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I split a String into an array in Kotlin?

I need to split a String read in from a file into an array of values. I want to split the String at the commas, so for example, if the String read:

"name, 2012, 2017" 

The values in the array would be:

  • array index 0 - name
  • array index 1 - 2012
  • array index 2 - 2017

I found this example in Java:

String[] stringArray = string.split(","); 

How I could do it in Kotlin?

like image 901
Michael F. Avatar asked Sep 04 '17 13:09

Michael F.


People also ask

How do you split a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What does .split do in Kotlin?

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

How do you split a string by space in Kotlin?

We can use the split() function to split a char sequence around matches of a regular expression. To split on whitespace characters, we can use the regex '\s' that denotes a whitespace character. Note that we have called the toTypedArray() function, since the split() function returns a list.


2 Answers

val strs = "name, 2012, 2017".split(",").toTypedArray() 
like image 178
JK Ly Avatar answered Oct 06 '22 05:10

JK Ly


If we have a string of values that splited by any character like ",":

 val values = "Name1 ,Name2, Name3" // Read List from somewhere  val lstValues: List<String> = values.split(",").map { it -> it.trim() }  lstValues.forEach { it ->                 Log.i("Values", "value=$it")                 //Do Something             } 

It's better to use trim() to delete spaces around strings if exist. Consider that if have a "," at the end of string it makes one null item, so can check it with this code before split :

 if ( values.endsWith(",") )      values = values.substring(0, values.length - 1) 

if you want to convert list to Array ,use this code:

      var  arr = lstValues.toTypedArray()       arr.forEach {  Log.i("ArrayItem", " Array item=" + it ) } 
like image 36
Hamed Jaliliani Avatar answered Oct 06 '22 05:10

Hamed Jaliliani