如何将一个分隔的字符串解析为子字符串的切片?

huangapple go评论82阅读模式
英文:

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", ",")

huangapple
  • 本文由 发表于 2015年1月19日 00:29:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/28012042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定