我正在尝试创建一个方法来转换字符串中的字符,特别是将所有'0‘转换为’‘。这是我使用的代码:
def removeZeros(s: String) = {
val charArray = s.toCharArray
charArray.map( c => if(c == '0') ' ')
new String(charArray)
}
有没有更简单的方法呢?此语法无效:
def removeZeros(s: String) =
new String(s.toCharArray.map( c => if(c == '0') ' '))
发布于 2014-01-21 23:10:43
您可以直接映射字符串:
def removeZero(s: String) = s.map(c => if(c == '0') ' ' else c)
或者,您可以使用replace
s.replace('0', ' ')
发布于 2014-01-21 23:10:38
非常简单:
scala> "FooN00b".filterNot(_ == '0')
res0: String = FooNb
要用其他字符替换某些字符,请执行以下操作:
scala> "FooN00b" map { case '0' => 'o' case 'N' => 'D' case c => c }
res1: String = FooDoob
要用任意数量的字符替换一个字符,请执行以下操作:
scala> "FooN00b" flatMap { case '0' => "oOo" case 'N' => "" case c => s"$c" }
res2: String = FoooOooOob
发布于 2019-08-16 01:55:40
根据Ignacio Alorre的说法,如果您想将其他字符替换为字符串:
def replaceChars (str: String) = str.map(c => if (c == '0') ' ' else if (c =='T') '_' else if (c=='-') '_' else if(c=='Z') '.' else c)
val charReplaced = replaceChars("N000TZ")
https://stackoverflow.com/questions/21261737
复制相似问题