String 如何从Scala中的字符串中删除子字符串/字符?
我正在编写一个程序,需要在其中过滤字符串。所以我有一个字符映射,我希望字符串过滤掉映射中没有的所有字符。我有办法做到这一点吗 假设我们有字符串和映射:String 如何从Scala中的字符串中删除子字符串/字符?,string,scala,filter,substring,String,Scala,Filter,Substring,我正在编写一个程序,需要在其中过滤字符串。所以我有一个字符映射,我希望字符串过滤掉映射中没有的所有字符。我有办法做到这一点吗 假设我们有字符串和映射: str = "ABCDABCDABCDABCDABCD" Map('A' -> "A", 'D' -> "D") 然后我希望字符串被过滤到: str = "BCBCBCBCBC" 另外,如果我在字符串中找到一个给定的子字符串,有没有办法用另一个子字符串替换它 例如,如果我们有字符串: "The number ten is ev
str = "ABCDABCDABCDABCDABCD"
Map('A' -> "A", 'D' -> "D")
然后我希望字符串被过滤到:
str = "BCBCBCBCBC"
另外,如果我在字符串中找到一个给定的子字符串,有没有办法用另一个子字符串替换它
例如,如果我们有字符串:
"The number ten is even"
我们是否可以用以下内容代替:
"The number 10 is even"
使用映射过滤字符串只是一个过滤命令:
val str = "ABCDABCDABCDABCDABCD"
val m = Map('A' -> "A", 'D' -> "D")
str.filterNot(elem => m.contains(elem))
string.replace("ten", "10")
注释中建议的更具功能的替代方案
str.filterNot(m.contains)
输出
scala> str.filterNot(elem => m.contains(elem))
res3: String = BCBCBCBCBC
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
替换字符串中的元素:
val str = "ABCDABCDABCDABCDABCD"
val m = Map('A' -> "A", 'D' -> "D")
str.filterNot(elem => m.contains(elem))
string.replace("ten", "10")
输出
scala> str.filterNot(elem => m.contains(elem))
res3: String = BCBCBCBCBC
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)
,这是一种更实用的方法,但对于初学者来说可能更容易混淆。如果您有Map('a'->“B','C'->“D”)
或者甚至Map('a'->“W','X'->“D”,该怎么办)
?那么应该如何过滤str
呢?如果你只需要一组字符,也许你应该使用Set
而不是Map
。