philantrovert
philantrovert

Reputation: 10082

Replace all elements of a Seq from a String

I have a String and a Seq like :

Array[String] = Array(a, the, an)

String = "This is a sentence that includes articles a, an and the"

I want to replace each element of the Seq within the String with ""

Currently, I'm doing something like :

val a = Array("a" , "the", "an" )
var str = "This is a sentence that includes articles a, an and the"
a.foldLeft( "" ){ (x,y) => str=str.replaceAll(s"\\b${x}\\b", ""); str }

It seems to be working but doesn't look very Scala-ish mostly because of the re-assignment of the string for each iteration.

Is there any other way to do this?

Upvotes: 1

Views: 692

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

It's just

a.foldLeft(str) { (x,y) => x.replaceAll(s"\\b${y}\\b", "") }

For foldLeft, x is already the intermediate result you want, no need to store it in a var.

(As a side note, your original code doesn't work correctly in general: if a is empty, it'll return "" instead of str.)

Upvotes: 1

Nyavro
Nyavro

Reputation: 8866

This seems to be the correct variant:

a.foldLeft(str){ case (acc,item) => acc.replaceAll(s"\\b${item}\\b", "")}

Upvotes: 2

Related Questions