Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing characters from List of Strings

Tags:

string

scala

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 ?

like image 989
blue-sky Avatar asked Dec 05 '22 02:12

blue-sky


1 Answers

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.

like image 118
om-nom-nom Avatar answered Dec 21 '22 08:12

om-nom-nom