Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why TrimLeft doesn't work as expected?

Tags:

go

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

like image 616
The user with no hat Avatar asked Mar 21 '15 19:03

The user with no hat


1 Answers

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.

like image 132
Arkadiusz Kałkus Avatar answered Sep 24 '22 23:09

Arkadiusz Kałkus