Why is TrimLeft not working as expected?

I expected the tag to be "account", but it is "ccount". Why is "a" deleted?

package main

import "fmt"
import "strings"

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

Run

+4
source share
2 answers

It works as documented :

TrimLeft returns a fragment of string s with all leading Unicode code points contained in the deletion pieces

Because in the first argument (cutset) "a", the leading "a" is deleted

+8
source

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)
}

Note that the following TrimLeft calls will result in 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)
}

, TrimLeft - , . , , , .

+7

All Articles