I am writing a function in go to clean individual words, thereby removing special characters at the beginning and end of each word.
Right now:
I get the following result by checking each end letter by letter to see if it belongs to the unicode.letter set, which works great, but I'm wondering if there is a better or more efficient way to do this? I tried strings.trimleft/right, but then I had to define my own set of characters to remove. It would be nice to use predefined collections.
func TrimWord(word []rune) string { var prefix int = 0 var suffix int = len(word) for x := 0; x < len(word); x++ { if !unicode.IsLetter(word[x]) { prefix++ } else { break } } for x := len(word) - 1; x >= 0; x-- { if suffix == prefix { break } if !unicode.IsLetter(word[x]) { suffix-- } else { break } } return string(word[prefix:suffix]) }
package main import ( "fmt" "strings" "unicode" ) func trimword(s string) string { return strings.trimfunc(s, func(r rune) bool { return !unicode.isletter(r) }) } func main() { fmt.println(trimword(`.-hello,`)) // -> hello fmt.println(trimword(`"back-to-back"`)) // -> back-to-back }
//m.sbmmt.com/link/55053683268957697aa39fba6f231c68
hello back-to-back
func TrimFunc(s string, f func(rune) bool) string
trimfunc returns a slice of string s with all leading and trailing unicode code points c removed that satisfy f(c).
The above is the detailed content of Remove special characters from words. For more information, please follow other related articles on the PHP Chinese website!