How to cut a string to a specific character in Go?

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

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

      

I want to be able to store "Rob"

(read before ':'

).

+3


source to share


2 answers


You can use strings.IndexByte()

or strings.IndexRune()

to get the position (byte index) of the colon ':'

and then just slice the value string

:

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

      

Output (try on Go Playground ):

Rob

      

If you are not sure what the colon is in string

, you need to check the index before moving on to the chunk string

, otherwise you will get panic at runtime. 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")
}

      

The conclusion is the same.

Modifying invalid message:



message := "Rob Hello everyone!"

      

Output this time (try on the Go Playground ):

Invalid string

      

Another convenient 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 on Go Playground ):

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

      

If string

there is no colon in the input , strings.Split()

returns a chunk of strings containing one value string

, which is the input (the code above does not print anything in this case, since the length will be 1

).

+4


source


strings.Index or strings.IndexRune , depending on whether you want to use unicode as the delimiter, you will get the index of the character you are looking for.

Alternatively, you can use strings.Split and just take the first returned string.

Example: user := strings.Split(message, ":")[0]



https://play.golang.org/p/I1P1Liz1F6

Notably, this will not panic if the delimiter character is not on the original line, but instead the variable user

will be set to the entire original line.

+1


source







All Articles