Home > OS >  How to split a string by a delimiter in Golang
How to split a string by a delimiter in Golang

Time:10-13

I want to split a string by a delimiter, and the result should be a slice.

For example:

The given string might be like this:

 foo := "foo=1&bar=2&&a=8"

The result should be like

 result := []string{
    "foo=1",
    "bar=2&",
    "a=8"
}

I mean i can use strings.split(foo, "&") to split but the result does not meet my requirements.

 // the result with strings.split()
 result := []string{
    "foo=1",
    "bar=2",
    "",
    "a=8"
}

CodePudding user response:

Why not use url.ParseQuery. If you need a special characters like & (which is the delimiter) to not be treated as such, then it needs to be escaped (&):

//m, err := url.ParseQuery("foo=1&bar=2&&a=8")
m, err := url.ParseQuery("foo=1&bar=2&&a=8") // escape bar's & as &


fmt.Println(m) // map[a:[8] bar:[2&] foo:[1]]

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


You would typically URL encode parameters like so:

q := url.Values{}

q.Add("foo", "1")
q.Add("bar", "2&")
q.Add("a", "8")

fmt.Println(q.Encode()) // a=8&bar=2&&foo=1

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

  • Related