Go语言strings.TrimRight函数结果不符预期,为何输出Hell而非Hello?
strings.TrimRight return "Hell" instead of "Hello"? Let's break down what's happening here—your confusion comes from misunderstanding how strings.TrimRight works in Go. It doesn't match and remove the entire cutset string from the end; instead, it removes individual characters from the end as long as they're present in the cutset, stopping only when it hits a character that's not in the set.
First, let's recap your code:
package main import ( "fmt" "strings" ) func main() { result := strings.TrimRight("Hello Gophers", " Gophers") fmt.Println(result, len(result)) // Output: Hell 4 }
Step-by-step breakdown of the trimming process
Your input string is "Hello Gophers", and the cutset " Gophers" includes these characters: ' ', 'G', 'o', 'p', 'h', 'e', 'r', 's'. Here's how trimming proceeds from the end:
's'is in the cutset → remove it →"Hello Gopher"'r'is in the cutset → remove it →"Hello Gophe"'e'is in the cutset → remove it →"Hello Goph"'h'is in the cutset → remove it →"Hello Gop"'p'is in the cutset → remove it →"Hello Go"'o'is in the cutset → remove it →"Hello G"'G'is in the cutset → remove it →"Hello "' 'is in the cutset → remove it →"Hello"- The last character now is
'o'—which is also in the cutset (since "Gophers" contains 'o') → remove it →"Hell" - Next character is
'l', which isn't in the cutset → trimming stops.
That's why you end up with "Hell"—the final 'o' in "Hello" is part of your cutset, so it gets trimmed too.
The fix: Use strings.TrimSuffix for exact suffix removal
If your goal is to remove the exact suffix " Gophers" from the string, strings.TrimSuffix is the right tool. It checks if the string ends with the specified suffix and removes it only if there's an exact match:
package main import ( "fmt" "strings" ) func main() { result := strings.TrimSuffix("Hello Gophers", " Gophers") fmt.Println(result, len(result)) // Output: Hello 5 }
内容的提问来源于stack exchange,提问作者Tahseen

