dongliyu3278
2015-01-18 16:29
浏览 21
已采纳

如何将定界字符串解析为子字符串切片?

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.

图片转代码服务由CSDN问答提供 功能建议

给出如下所示的URL:

  http:/  /127.0.0.1:3001/find?fields=主机名,App,Node_type,无效
   
 
 

我将字段提取为这样的切片:

 过滤器:= r.URL.Query()。Get(“ fields”)
fmt.Println(filters)
   
 
 

结果 :

 主机名,App,Node_type,无效
   
 
 

它作为字符串接收,但是我想 宁愿将子字符串分成一个序列。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongwuwan5646 2015-01-18 17:02
    已采纳

    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", ",")
    
    已采纳该答案
    打赏 评论
  • dongmao9217 2015-01-18 16:59

    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.

    打赏 评论

相关推荐 更多相似问题