使用 Scala 删除字符串中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39136428/
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-10-22 08:34:23  来源:igfitidea点击:

Remove whitespaces in string with Scala

scala

提问by madagascar

I want to remove the whitespaces in a string.

我想删除字符串中的空格。

Input: "le ngoc ky quang"  
Output: "lengockyquang"

I tried the replaceand replaceAllmethods but that did't work.

我尝试了replacereplaceAll方法,但没有奏效。

回答by Nyavro

Try the following:

请尝试以下操作:

input.replaceAll("\s", "")

回答by Volodymyr Kozubal

You can filter out all whitespace characters.

您可以过滤掉所有空白字符。

"With spaces".filterNot((x: Char) => x.isWhitespace)

回答by elm

Consider splitting the string by any number of whitespace characters (\\s+) and then re-concatenating the split array,

考虑用任意数量的空白字符 ( \\s+)拆分字符串,然后重新连接拆分的数组,

str.split("\s+").mkString

回答by TheKojuEffect

val str = "le ngoc ky quang"
str.replace(" ", "")

//////////////////////////////////////
scala> val str = "le ngoc ky quang"
str: String = le ngoc ky quang

scala> str.replace(" ", "")
res0: String = lengockyquang

scala> 

回答by azatprog

According to alvinalexanderit shows there how to replace more than white spaces to one space. The same logic you can apply, but instead of one space you should replace to empty string.

根据alvinalexander 的说法,它展示了如何将多个空格替换为一个空格。您可以应用相同的逻辑,但您应该替换为空字符串而不是一个空格。

input.replaceAll(" +", "")