Michael Pietzsch
Michael Pietzsch

Reputation: 145

How to replace multiple characters in the same string?

I am not very versed in programming in general so please cut me some slack here. Is there a more elegant way to tackle this process of replacing multiple characters in a string?

strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(godiacritics.Normalize(strings.ToLower(articles[i].Name)), "-", "_"), " ", "_"), ",", "_"), ".", ""), "/", ""), "€", ""), "%", ""), "12", "halb"), "14", "viertel")

Upvotes: 6

Views: 3540

Answers (1)

icza
icza

Reputation: 417572

Create a single strings.Replacer which contains all replaceable pairs:

r := strings.NewReplacer(
    "-", "_",
    " ", "_",
    ",", "_",
    ".", "",
    "/", "",
    "€", "",
    "%", "",
    "12", "halb",
    "14", "viertel",
)

And use it like this:

s2 := r.Replace(godiacritics.Normalize(strings.ToLower(articles[i].Name)))

strings.Replacer performs all replaces in a single step (it iterates over the string once). It's also safe for concurrent use, create the Replacer onces and reuse it whenever / wherever needed.

Example code to test it:

s := "test- ,./€%:12 14"
s2 := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(s, "-", "_"), " ", "_"), ",", "_"), ".", ""), "/", ""), "€", ""), "%", ""), "12", "halb"), "14", "viertel")
fmt.Println(s2)

r := strings.NewReplacer(
    "-", "_",
    " ", "_",
    ",", "_",
    ".", "",
    "/", "",
    "€", "",
    "%", "",
    "12", "halb",
    "14", "viertel",
)

s3 := r.Replace(s)
fmt.Println(s3)

Which outputs (try it on the Go Playground):

test___:halb_viertel
test___:halb_viertel

Upvotes: 15

Related Questions