Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string only by the first element in golang

Tags:

slice

split

go

I'm trying to parse git branch names and split them so I can seperate the remote and the branch name

Previously I just split on the first slash:

func ParseBranchname(branchString string) (remote, branchname string) {
    branchArray := strings.Split(branchString, "/")
    remote = branchArray[0]
    branchname = branchArray[1]
    return
}

But I forgot that some folks use slashes in git branch names as well, multiple even!

Right now I'm taking the first element in the slice from the split, then moving every element one done and merging back on the slash:

func ParseBranchname(branchString string) (remote, branchname string) {
    branchArray := strings.Split(branchString, "/")
    remote = branchArray[0]

    copy(branchArray[0:], branchArray[0+1:])
    branchArray[len(branchArray)-1] = ""
    branchArray = branchArray[:len(branchArray)-1]

    branchname = strings.Join(branchArray, "/")
    return
}

Is there a cleaner way to do this?

like image 844
Peter Souter Avatar asked Nov 25 '25 15:11

Peter Souter


1 Answers

For Go >= 1.18 see this answer.


For Go < 1.18:

Use strings.SplitN with n=2 to limit the result to two substrings.

func ParseBranchname(branchString string) (remote, branchname string) {
    branchArray := strings.SplitN(branchString, "/", 2)
    remote = branchArray[0]
    branchname = branchArray[1]
    return
}
like image 170
Jonathon Reinhart Avatar answered Nov 28 '25 08:11

Jonathon Reinhart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!