Search code examples
stringgosubstringslice

How to slice string till particular character in Go?


I want to extract a string till a character is found. For example:

message := "Rob: Hello everyone!"
user := strings.Trim(message,

I want to be able to store "Rob" (read till ':' is found).


Solution

  • You may use strings.IndexByte() or strings.IndexRune() to get the position (byte-index) of the colon ':', then simply slice the string value:

    message := "Rob: Hello everyone!"
    user := message[:strings.IndexByte(message, ':')]
    fmt.Println(user)
    

    Output (try it on the Go Playground):

    Rob
    

    If you're not sure the colon is in the string, you have to check the index before proceeding to slice the string, else you get a runtime panic. This is how you can do it:

    message := "Rob: Hello everyone!"
    if idx := strings.IndexByte(message, ':'); idx >= 0 {
        user := message[:idx]
        fmt.Println(user)
    } else {
        fmt.Println("Invalid string")
    }
    

    Output is the same.

    Changing the message to be invalid:

    message := "Rob Hello everyone!"
    

    Output this time is (try it on the Go Playground):

    Invalid string
    

    Another handy solution is to use strings.Split():

    message := "Rob: Hello everyone!"
    
    parts := strings.Split(message, ":")
    fmt.Printf("%q\n", parts)
    
    if len(parts) > 1 {
        fmt.Println("User:", parts[0])
    }
    

    Output (try it on the Go Playground):

    ["Rob" " Hello everyone!"]
    User: Rob
    

    Should there be no colon in the input string, strings.Split() returns a slice of strings containing a single string value being the input (the code above does not print anything in that case as length will be 1).