英文:
Golang - split string into at most N parts?
问题
// 解析请求
parts := strings.SplitN(message, ",", 2)
uuid := parts[0]
data := parts[1]
上述代码通过,将message分割成多个部分,但实际上我只想要两个部分。但是data部分本身可能包含,,所以它可能被分割成多于两个部分。
例如
我想要将字符串分割为:
"19177360-2765-4597-a58e-519783a0d51d,a,b,c"
分割结果应为:
["19177360-2765-4597-a58e-519783a0d51d", "a,b,c"]
而不是:
["19177360-2765-4597-a58e-519783a0d51d", "a", "b", "c"]
可能的解决方案
使用strings.SplitN(message, ",", 2),它将分割成4个部分。我可以搜索第一个,,然后手动获取子字符串。
问题
但是是否有一种方便的函数可以指定将字符串分割为最多N个部分的方法。
Java中有针对String的内置方法,是否有类似的Go库可以用于string?
谢谢。
英文:
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
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.
答案1
得分: 5
strings.SplitN 是你想要的函数,第三个参数是你想要拆分的部分数量:
arrayString := strings.SplitN(message, ",", 2)
// arrayString[0] = 19177360-2765-4597-a58e-519783a0d51d
// arrayString[1] = a,b,c
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论