Java 如何在 Kotlin 中将字符串拆分为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46038476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:15:21  来源:igfitidea点击:

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

javaarraysstringkotlin

提问by Michael F.

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
  • 数组索引 0 - 名称
  • 数组索引 1 - 2012
  • 数组索引 2 - 2017

I found this example in Java:

我在 Java 中找到了这个例子:

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

How I could do it in Kotlin?

我怎么能在 Kotlin 中做到这一点?

采纳答案by JK Ly

val strs = "name, 2012, 2017".split(",").toTypedArray()

回答by Hamed Jaliliani

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 :

如果存在,最好使用 trim() 删除字符串周围的空格。考虑到如果在字符串末尾有一个“,”,它会生成一个空项,因此可以在 split 之前使用以下代码进行检查:

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

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

如果要将 list 转换为 Array ,请使用以下代码:

      var  arr = lstValues.toTypedArray()
      arr.forEach {  Log.i("ArrayItem", " Array item=" + it ) }

回答by Thiago Silva

Simple as it is:

很简单:

val string: String = "leo_Ana_John"
val yourArray: List<String> = string.split("_")

you get: yourArray[0] == leo, yourArray[1] == Ana, yourArray[2]==John

你得到: yourArray[0] == leo, yourArray[1] == Ana, yourArray[2]==John

回答by Manikandan

Split a string using inbuilt split method then using method extensions isNum() to return numeric or not.

使用内置的拆分方法拆分字符串,然后使用方法扩展 isNum() 返回数字或不返回。

fun String.isNum(): Boolean{
   var num:Int? = this.trim().toIntOrNull()
   return if (num != null) true else false
}

for (x in "name, 2012, 2017".split(",")) {
   println(x.isNum())
}