user1028741
user1028741

Reputation: 2815

Go (strings) - Trim repeated prefix/suffix substring

I need to trim a repeated prefix and suffix substring ("%20") of a string.
Example: %20%20Hello%20World%20%20 --> Hello%20World

The best I could come with is something like:

func trimPrefix(s string, prefix string) string {
    for ; strings.HasPrefix(s, prefix); {
        s = s[len(prefix):]
    }
    return s
}

func trimSuffix(s string, suffix string) string {
    for ; strings.HasSuffix(s, suffix); {
        s = s[:len(s)-len(suffix)]
    }
    return s
}

func trim(s, ss string) string {
    return trimPrefix(trimSuffix(s, ss), ss)
}

Is there a more elegant way to do it in Go?

Upvotes: 3

Views: 3065

Answers (2)

mkopriva
mkopriva

Reputation: 38233

You can do the following:

func trimSubstr(s string, substr string) (t string) {
    for {
        t = strings.TrimPrefix(s, substr)
        t = strings.TrimSuffix(t, substr)
        if t == s { // exit if nothing was trimmed from s
            break
        }
        s = t // update to last result
    }
    return t
}

https://go.dev/play/p/eIk6A8K3Q_1

Upvotes: 3

blackgreen
blackgreen

Reputation: 44767

strings.Trim does that

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "%20%20Hello%20World%20%20"
    t := strings.Trim(s, "%20")

    fmt.Println(t) // prints Hello%20World
}

This works just fine if your prefix and suffix runes always appear in the same order given in cutset param.

If your input string may present those characters in different orders (see comments to this answer for details), then your solution is good. You can use strings.TrimPrefix and strings.TrimSuffix from the standard lib instead of rolling your own, and combine it in one function:

func trim(s, sub string) string {
    for strings.HasPrefix(s, sub) {
        s = strings.TrimPrefix(s, sub)
    }
    for strings.HasSuffix(s, sub) {
        s = strings.TrimSuffix(s, sub)
    }
    return s
}

Upvotes: 3

Related Questions