英文:
How do I parse a delimited string into a slice of substrings?
问题
给定以下URL:
http://127.0.0.1:3001/find?fields=hostname,App,Node_type,invalid
我将提取字段并将其存储在一个切片中,代码如下:
filters := r.URL.Query().Get("fields")
fmt.Println(filters)
结果为:
hostname,App,Node_type,invalid
目前这个结果是一个字符串,但我更希望将其分割成一个序列。
英文:
Given a URL like the following:
http://127.0.0.1:3001/find?fields=hostname,App,Node_type,invalid
I extract fields into a slice like this:
filters := r.URL.Query().Get("fields")
fmt.Println(filters)
Result:
hostname,App,Node_type,invalid
It is received as a string, but I'd prefer to separate the substrings into a sequence.
答案1
得分: 1
这个问题实际上涉及如何根据特定的分隔符拆分字符串。为此,你可以使用strings.Split()
函数:
import "strings"
// ...
filters := strings.Split(r.URL.Query().Get("fields"), ",")
现在,你的filters
变量将是一个切片,如果没有可用的"fields"查询参数,它可能为空。
英文:
The question actually concerns how to split a string on a particular delimiter. For that, you can use the strings.Split()
function:
import "strings"
// ...
filters := strings.Split(r.URL.Query().Get("fields"), ",")
Your filters
variable will now be a slice, which may be empty if there was no "fields" query parameter available.
答案2
得分: 1
我认为你的URL应该是:
http://127.0.0.1:3001/find?fields=hostname&fields=App&fields=Node_type&fields=invalid
或者如果你不喜欢那个,你可以解析:
filterSlice:=strings.Split("filters", ",")
英文:
I think your URL should be
http://127.0.0.1:3001/find?fields=hostname&fields=App&fields=Node_type&fields=invalid
or if you don't like that, you can parse
filterSlice:=strings.Split("filters", ",")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论