【问题标题】:How do I remove a substring/character from a string in Scala?如何从 Scala 中的字符串中删除子字符串/字符?
【发布时间】:2020-01-13 18:45:19
【问题描述】:

我正在编写一个需要过滤字符串的程序。所以我有一个字符映射,我希望字符串过滤掉所有不在映射中的字符。我有办法做到这一点吗?

假设我们有字符串和地图:

str = "ABCDABCDABCDABCDABCD"

Map('A' -> "A", 'D' -> "D") 

然后我希望将字符串过滤为:

str = "BCBCBCBCBC"

另外,如果我在字符串中找到给定的子字符串,有没有办法可以用不同的子字符串替换它?

例如,如果我们有字符串:

"The number ten is even"

我们可以将其替换为:

"The number 10 is even"

【问题讨论】:

  • 如果你有Map('A' -> "B", 'C' -> "D") 甚至Map('A' -> "W", 'X' -> "D") 会怎样?那么应该如何过滤str
  • 如果你只需要Set个字符,也许你应该使用Set而不是Map

标签: string scala filter substring


【解决方案1】:

用地图过滤字符串只是一个过滤命令:

val str = "ABCDABCDABCDABCDABCD"
val m = Map('A' -> "A", 'D' -> "D")

str.filterNot(elem => m.contains(elem))

cmets 推荐的更实用的替代方案

str.filterNot(m.contains)

输出

scala> str.filterNot(elem => m.contains(elem))
res3: String = BCBCBCBCBC

替换字符串中的元素:

string.replace("ten", "10")

输出

scala> val s  = "The number ten is even"
s: String = The number ten is even

scala> s.replace("ten", "10")
res4: String = The number 10 is even

【讨论】:

  • 很高兴为您提供帮助,请接受答案,以便任何有相同问题的人都能快速找到答案
  • 这可以简化为str.filterNot(m.contains),这是一种更实用的方法,但对于初学者来说可能更容易混淆。
猜你喜欢
  • 2019-09-08
  • 1970-01-01
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多