如何将句子拆分为多个空格分隔的单词? [英] How to split sentence into words separated by multiple spaces?
本文介绍了如何将句子拆分为多个空格分隔的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码:
val sentence = "1 2 3 4".split(" ")
给我:
Array(1, 2, "", 3, "", "", 4)
但我宁愿只有单词:
Array(1, 2, 3, 4)
当单词被多个空格分隔时,如何拆分句子?
How can I split the sentence when the words are separated by multiple spaces?
推荐答案
使用正则表达式:
scala> "1 2 3".split(" +")
res1: Array[String] = Array(1, 2, 3)
+"表示前一个或多个"(前一个是空格).
The "+" means "one or more of the previous" (previous being a space).
更好的是,如果您想在所有空白处进行拆分:
Better yet, if you want to split on all whitespace:
scala> "1 2 3".split("\\s+")
res2: Array[String] = Array(1, 2, 3)
(其中 "\\s"
是 模式 匹配任何空格.查看这里 获取更多示例.)
(Where "\\s"
is a Pattern which matches any whitespace. Look here for more examples.)
这篇关于如何将句子拆分为多个空格分隔的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文