hp10 hp10 - 1 year ago 71
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 Source

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 ) => 

Outputs: abc

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download