Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang – split string into at most N parts?

Code & problem

// parse request,
parts := strings.Split(message, ",")
uuid := parts[0]
data := parts[1]

The above code split message by ,, I actually want 2 parts.
But the data part itself may contain ,, so it may be split into more than 2 parts.


e.g

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to split string:
"19177360-2765-4597-a58e-519783a0d51d,a,b,c"
into:
["19177360-2765-4597-a58e-519783a0d51d", "a,b,c"]
not:
["19177360-2765-4597-a58e-519783a0d51d", "a", "b", "c"]


Possible solution

With strings.Split(message, ","), it split into 4 parts.
I can search for first ,, then get substrings by hand.


Question

But is there a convenient function to specify the max N parts to split the string into.

Java has such built-in methods for String, is there similar Go libraries for string ?

Thanks.

>Solution :

strings.SplitN is the function that you wants, the third parameter is the number of parts that you want to split:

arrayString := strings.SplitN(message, ",", 2)
// arrayString[0] = 19177360-2765-4597-a58e-519783a0d51d
// arrayString[1] = a,b,c

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading