为什么 TrimLeft 不按预期工作?

huangapple go评论83阅读模式
英文:

Why TrimLeft doesn't work as expected?

问题

我预期标签应该是"account",但实际上是"ccount"。为什么"a"被移除了?

package main

import "fmt"
import "strings"

func main() {
    s := "refs/tags/account"
    tag := strings.TrimLeft(s, "refs/tags")
    fmt.Println(tag)
}

运行

英文:

I've expected tag to be "account" but it is "ccount". Why is "a" removed?

package main

import "fmt"
import "strings"

func main() {
	s := "refs/tags/account"
	tag := strings.TrimLeft(s, "refs/tags")
	fmt.Println(tag)
}

Run

答案1

得分: 12

使用TrimPrefix而不是TrimLeft

package main

import "fmt"
import "strings"

func main() {
    s := "refs/tags/account"
    tag := strings.TrimPrefix(s, "refs/tags/")
    fmt.Println(tag)
}

请注意,以下的TrimLeft调用将得到相同的字符串"fghijk":

package main

import (
        "fmt"
        "strings"
)

func main() {
    s := "/abcde/fghijk"
    tag := strings.TrimLeft(s, "/abcde")
    fmt.Println(tag)    
    tag = strings.TrimLeft(s, "/edcba")
    fmt.Println(tag)
}

所以TrimLeft不是适合你需求的方法。我猜在你给出的示例中使用它无法得到你期望的结果。

英文:

Use TrimPrefix instead of TrimLeft

package main

import "fmt"
import "strings"

func main() {
    s := "refs/tags/account"
    tag := strings.TrimPrefix(s, "refs/tags/")
    fmt.Println(tag)
}

Please notice that following TrimLeft calls will result the same "fghijk
" string:

package main

import (
        "fmt"
        "strings"
)

func main() {
	s := "/abcde/fghijk"
	tag := strings.TrimLeft(s, "/abcde")
	fmt.Println(tag)	
	tag = strings.TrimLeft(s, "/edcba")
	fmt.Println(tag)
}

So TrimLeft is not the method which fits your needs. I guess it's impossible to use it in the example you've given to get the result you expect.

答案2

得分: 10

根据文档的描述,它正在按预期工作:

TrimLeft 返回字符串 s 的一个切片,其中移除了 cutset 中包含的所有前导 Unicode 代码点

由于第一个参数(cutset)中有一个 'a',所以account中的前导 'a' 被移除了。

英文:

It is working as documented:

> TrimLeft returns a slice of the string s with all leading Unicode
> code points contained in cutset removed

Because there's an 'a' in the first argument (the cutset) the leading 'a' in account is removed

huangapple
  • 本文由 发表于 2015年3月22日 03:30:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/29187086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定