英文:
How Can I Remove White Space In String Array?
问题
我正在尝试使用arrayOf中的项来创建一个列表。然而,当我执行toList().toString()来处理strArray时,每个项之间都有一个空格,我想去掉这个空格。如下面的图片所示:当我使用replace(" ", "")时,它解决了这个问题,但也移除了项与数字之间的空格。如何在移除每个项之间的空格的同时保留项与数字之间的空格?如果您查看下面的图片,logcat的列表是正确的,但在Item1和其他项之间没有空格。我希望它显示Item 1等等。我已经进行了2个小时的尝试和错误,也在网上做了一些研究,但似乎找不到解决办法。感谢您的帮助!谢谢!
这是我的代码...
private fun strArrayInListForm() {
val strArray = arrayOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
val splitItems: String = strArray.toList().toString()
val getItems: String = splitItems.split(",").joinToString("\n")
.replace("[", "").replace("]", "")
.replace(" ", "")
println(getItems)
}
英文:
I am trying to form a list with the items in arrayOf. However, when I toList().toString that strArray between each item there is a white space that I am trying to get rid of. As you can see in the picture below; when I use replace( " ", "") it takes care of that, but it's also removing the white space between Item and the number. How can I remove the white space between each item without removing the white space between the item and number? If you look at the picture below; the logcat lists correctly, but there's no space between Item1 and the rest of the items. I want it to show Item 1 and so on. I've been doing trial and error for 2 hours, and I have been doing some researches online, and I can't seem to find a solution. I appreciate the help! Thanks!
Here is my code...
private fun strArrayInListForm() {
val strArray = arrayOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
val splitItems: String = strArray.toList().toString()
val getItems: String = splitItems.split(",").joinToString("\n")
.replace("[", "").replace("]", "")
.replace(" ", "")
println(getItems)
}
答案1
得分: 0
你可以在将列表转换为字符串并使用换行分隔符连接之前修剪列表中的字符串。
英文:
You can trim the strings in the list before converting it to a string and then joining with a newline delimiter.
答案2
得分: 0
我认为你应该在toString()之后直接用"\n"替换", ",而不是通过","拆分等等,像这样:
val strArray = arrayOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
val splitItems: String = strArray.toList().toString().replace(", ", "\n")
val getItems: String = splitItems
.replace("[", "").replace("]", "")
println(getItems)
英文:
I think you should replace the ", " with "\n" directly after your toString() instead of splitting by "," and all that, like this:
val strArray = arrayOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
val splitItems: String = strArray.toList().toString().replace(", ", "\n")
val getItems: String = splitItems
.replace("[", "").replace("]", "")
println(getItems)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论