简体   繁体   中英

How do I remove a substring/character from a string in Scala?

I am writing a program in which I need to filter a string. So I have a map of characters, and I want the string to filter out all characters that are not in the map. Is there a way for me to do this?

Let's say we have the string and map:

str = "ABCDABCDABCDABCDABCD"

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

Then I want the string to be filtered down to:

str = "BCBCBCBCBC"

Also, if I find a given substring in the string, is there a way I can replace that with a different substring?

So for example, if we have the string:

"The number ten is even"

Could we replace that with:

"The number 10 is even"

To filter the String with the map is just a filter command:

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

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

A more functional alternative as recommended in comments

str.filterNot(m.contains)

Output

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

To replace elements in the String:

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

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM