To remove characters from a List of Strings I use :
val validLines : List[String] = List("test[" , "test]")
val charsToClean: List[String] = List("\"", "[", "]", "'")
val filtered = validLines.map(line => line.replace(charsToClean(0), "")
.replace(charsToClean(1), "")
.replace(charsToClean(2), "")
.replace(charsToClean(3), ""))
I'm attempting use a inner map function instead of hard coding the positions of the chars to replace :
val filtered1 : List[String] = validLines.map(line => charsToClean.map {c => line.replace(c , "") })
But receive compiler error :
mismatch; found : List[List[String]] required: List[String]
Should result of line.replace(c , "")
not be returned ?
No, because your code is more like: for every string and for every unwanted char, return replacement for this very symbol (n^2 strings).
What you probably wanted to do can be achieved using the following snippet:
val rawLines : List[String] = List("test[" , "test]")
val blacklist: Set[Char] = Set('\"', '[', ']' ,''')
rawLines.map(line => line.filterNot(c => blacklist.contains(c)))
// res2: List[String] = List(test, test)
Or alternatively, using regexp, as @ka4eli has shown in his answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With