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"
2
  • 1
    What if you had Map('A' -> "B", 'C' -> "D") or maybe even Map('A' -> "W", 'X' -> "D")? How then should str be filtered? Commented Jan 13, 2020 at 11:22
  • If you only need to have a Set of characters, maybe you should use a Set instead of a Map. Commented Jan 13, 2020 at 11:46

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Glad to help, please, accept the answer so anyone with the same question can reach to it quickly
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.