I need to trim a repeated prefix and suffix substring (" "
) of a string.
Example: Hello World
--> Hello World
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?
CodePudding user response:
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
CodePudding user response:
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 := " Hello World "
t := strings.Trim(s, " ")
fmt.Println(t) // prints Hello World
}
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
}