You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言strings.TrimRight函数结果不符预期,为何输出Hell而非Hello?

Why does 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:

  1. 's' is in the cutset → remove it → "Hello Gopher"
  2. 'r' is in the cutset → remove it → "Hello Gophe"
  3. 'e' is in the cutset → remove it → "Hello Goph"
  4. 'h' is in the cutset → remove it → "Hello Gop"
  5. 'p' is in the cutset → remove it → "Hello Go"
  6. 'o' is in the cutset → remove it → "Hello G"
  7. 'G' is in the cutset → remove it → "Hello "
  8. ' ' is in the cutset → remove it → "Hello"
  9. The last character now is 'o'—which is also in the cutset (since "Gophers" contains 'o') → remove it → "Hell"
  10. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:10:33