hp10 hp10 - 21 days ago 5
Scala Question

Scala : Idiomatic way of removing set of suffixes (substrings) from a String

I'm looking for an idiomatic way of stripping set of suffixes (substrings) from a string in Scala.

val inputString = "abc@xyz.com"
val suffixes = List("\"", "@xyz.com")


Basically, the suffixes list is loaded externally and hence not static. Therefore I cannot use the approach of chaining stripSuffix methods

(P.S. - I'll remove the starting " using inputString.stripPrefix("\"")

Answer

You could used a foldLeft to along with the .stripSuffix() function to iterate over your dynamic list of suffixes and strip them from your string one-by-one.

val inputString = "abc@xyz.com"
val suffixes = List("\"", "@xyz.com")
val strippedString = suffixes.foldLeft(inputString) { (string, suffix ) => 
    string.stripSuffix(suffix)
}

Outputs: abc

With this approach the order of your suffixes will impact your output.