Trim strings (remove chars or substrings)
suggest changestrings.TrimSpace
strings.TrimSpace(s string)
removes whitespace from the beginning and end of the string:
s := " str\n "
fmt.Printf("TrimSpace: %#v => %#v\n", s, strings.TrimSpace(s))
TrimSpace: " str\n " => "str"
strings.TrimPrefix, strings.TrimSuffix
strings.TrimPrefix
and strings.TrimSuffix
remove a given string from the beginning or end of string:
prefix := "aba"
s1 := "abacdda"
trimmed1 := strings.TrimPrefix(s1, prefix)
fmt.Printf("TrimPrefix %#v of %#v => %#v\n\n", prefix, s1, trimmed1)
s2 := "abacdda"
suffix := "da"
trimmed2 := strings.TrimSuffix(s2, suffix)
fmt.Printf("TrimSuffix %#v of %#v => %#v\n\n", suffix, s2, trimmed2)
TrimPrefix "aba" of "abacdda" => "cdda"
TrimSuffix "da" of "abacdda" => "abacd"
strings.Trim
strings.Trim
removes all characters from a given cut set from a string:
s := "abacdda"
cutset := "zab"
trimmed := strings.Trim(s, cutset)
fmt.Printf("Trim chars %#v from %#v => %#v\n\n", cutset, s, trimmed)
trimmed = strings.TrimLeft(s, cutset)
fmt.Printf("TrimLeft chars %#v from %#v => %#v\n\n", cutset, s, trimmed)
trimmed = strings.TrimRight(s, cutset)
fmt.Printf("TrimRight chars %#v from %#v => %#v\n\n", cutset, s, trimmed)
Trim chars "zab" from "abacdda" => "cdd"
TrimLeft chars "zab" from "abacdda" => "cdda"
TrimRight chars "zab" from "abacdda" => "abacdd"
strings.Replace
To remove substrings you can replace with empty string:
s := "this is string"
toRemove := " is"
after := strings.Replace(s, toRemove, "", -1)
fmt.Printf("Removed %#v from %#v => %#v\n\n", toRemove, s, after)
Removed " is" from "this is string" => "this string"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents