简体   繁体   English

为什么TrimLeft不能按预期工作?

[英]Why TrimLeft doesn't work as expected?

I've expected tag to be "account" but it is "ccount". 我希望标签是“帐户”,但它是“ccount”。 Why is "a" removed? 为什么删除“a”?

package main

import "fmt"
import "strings"

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

Run

It is working as documented : 按照记录的方式工作:

TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed TrimLeft返回字符串s的一个片段,其中包含cutset中包含的所有前导Unicode代码点

Because there's an 'a' in the first argument (the cutset) the leading 'a' in account is removed 因为第一个参数(cutset)中有一个'a',所以帐户中的前导'a'被删除

Use TrimPrefix instead of TrimLeft 使用TrimPrefix而不是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: 请注意,在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)
}

So TrimLeft is not the method which fits your needs. 所以TrimLeft不是适合您需求的方法。 I guess it's impossible to use it in the example you've given to get the result you expect. 我想在你给出的例子中使用它是不可能的,以获得你期望的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM