2

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"
LondonMassive
  • 367
  • 2
  • 5
  • 20

1 Answers1

3

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
SCouto
  • 7,808
  • 5
  • 32
  • 49
  • Glad to help, please, accept the answer so anyone with the same question can reach to it quickly – SCouto Jan 13 '20 at 10:12
  • 2
    This can be simplified to `str.filterNot(m.contains)` which is a more functional way of doing it, but perhaps more confusing for a beginner. – Tim Jan 13 '20 at 10:38