Parse string into map Golang

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

Parse string into map Golang

问题

我可以帮你翻译这段代码。这段代码是用Java实现的,用于将字符串解析为映射(Map)。下面是对应的Golang代码:

package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "A=B&C=D&E=F"
	pairs := strings.Split(text, "&")
	
	m := make(map[string]string)
	for _, pair := range pairs {
		keyValue := strings.Split(pair, "=")
		key := keyValue[0]
		value := ""
		if len(keyValue) > 1 {
			value = keyValue[1]
		}
		m[key] = value
	}
	
	fmt.Println(m)
}

这段代码首先使用strings.Split函数将字符串按照"&"分割成多个键值对。然后,使用循环遍历每个键值对,再使用strings.Split函数将键值对按照"="分割成键和值。最后,将键值对存入一个map中。

希望对你有帮助!

英文:

I have a string like A=B&C=D&E=F, how to parse it into map in golang?

Here is example on Java, but I don't understand this split part

String text = "A=B&C=D&E=F";
Map<String, String> map = new LinkedHashMap<String, String>();
for(String keyValue : text.split(" *& *")) {
   String[] pairs = keyValue.split(" *= *", 2);
   map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]);
}

答案1

得分: 11

也许你真正想要的是解析一个HTTP查询字符串,url.ParseQuery可以做到这一点。(更准确地说,它返回一个url.Values,其中存储了每个键的[]string,因为URL有时会有多个值对应一个键。)它可以解析HTML转义字符(%0A等),而仅仅使用分割是无法做到的。如果你在 url.go 的源代码中搜索,就可以找到它的实现。

然而,如果你确实只想像Java代码那样按&=进行分割,Go语言中也有类似的概念和工具:

  • map[string]string 是Go语言中类似于 Map<String, String> 的结构。
  • strings.Split 可以按&进行分割。SplitN 可以限制分割的片段数,就像Java中的两个参数的split()函数一样。请注意,可能只有一个片段,所以在尝试访问pieces[1]之前,应该检查len(pieces)
  • for _, piece := range pieces 可以遍历你分割的片段。
  • Java代码似乎依赖于正则表达式来去除空格。Go语言的Split函数没有使用正则表达式,但strings.TrimSpace可以做到类似的效果(具体来说,它会从两端去除各种Unicode空白字符)。

我将实际的实现留给你,但也许这些提示可以帮助你入门。

英文:

Maybe what you really want is to parse an HTTP query string, and url.ParseQuery does that. (What it returns is, more precisely, a url.Values storing a []string for every key, since URLs sometimes have more than one value per key.) It does things like parse HTML escapes (%0A, etc.) that just splitting doesn't. You can find its implementation if you search in the source of url.go.

However, if you do really want to just split on & and = like that Java code did, there are Go analogues for all of the concepts and tools there:

  • map[string]string is Go's analog of Map<String, String>
  • strings.Split can split on & for you. SplitN limits the number of pieces split into like the two-argument version of split() in Java does. Note that there might only be one piece so you should check len(pieces) before trying to access pieces[1] say.
  • for _, piece := range pieces will iterate the pieces you split.
  • The Java code seems to rely on regexes to trim spaces. Go's Split doesn't use them, but strings.TrimSpace does something like what you want (specifically, strips all sorts of Unicode whitespace from both sides).

I'm leaving the actual implementation to you, but perhaps these pointers can get you started.

答案2

得分: 10

import (
    "strings"
)

var m map[string]string
var ss []string

s := "A=B&C=D&E=F"
ss = strings.Split(s, "&")
m = make(map[string]string)
for _, pair := range ss {
    z := strings.Split(pair, "=")
    m[z[0]] = z[1]
}

这段代码会实现你想要的功能。

英文:
import ( "strings" )

var m map[string]string
var ss []string

s := "A=B&C=D&E=F"
ss = strings.Split(s, "&")
m = make(map[string]string)
for _, pair := range ss {
	z := strings.Split(pair, "=")
	m[z[0]] = z[1]
}

This will do what you want.

答案3

得分: 0

有一个非常简单的方法,由golang的net/url包本身提供。

将你的字符串更改为带有查询参数的URL,例如 text := "method://abc.xyz/A=B&C=D&E=F";

现在只需将此字符串传递给net/url提供的Parse函数。

import (
    netURL "net/url"
)
u, err := netURL.Parse(textURL)
if err != nil {
    log.Fatal(err)
}

现在u.Query()将返回一个包含查询参数的映射。这也适用于复杂类型。

英文:

There is a very simple way provided by golang net/url package itself.

Change your string to make it a url with query params text := "method://abc.xyz/A=B&C=D&E=F";

Now just pass this string to Parse function provided by net/url.

import (
    netURL "net/url"
)
u, err := netURL.Parse(textURL)
		if err != nil {
			log.Fatal(err)
		}

Now u.Query() will return you a map containing your query params. This will also work for complex types.

答案4

得分: 0

这是一些方法的演示:

package main

import (
   "fmt"
   "net/url"
)

func main() {
   {
      q, e := url.ParseQuery("west=left&east=right")
      if e != nil {
         panic(e)
      }
      fmt.Println(q) // map[east:[right] west:[left]]
   }
   {
      u := url.URL{RawQuery: "west=left&east=right"}
      q := u.Query()
      fmt.Println(q) // map[east:[right] west:[left]]
   }
}
英文:

Here is a demonstration of a couple of methods:

package main

import (
   "fmt"
   "net/url"
)

func main() {
   {
      q, e := url.ParseQuery("west=left&east=right")
      if e != nil {
         panic(e)
      }
      fmt.Println(q) // map[east:[right] west:[left]]
   }
   {
      u := url.URL{RawQuery: "west=left&east=right"}
      q := u.Query()
      fmt.Println(q) // map[east:[right] west:[left]]
   }
}

huangapple
  • 本文由 发表于 2016年2月27日 07:59:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/35663892.html
匿名

发表评论

匿名网友

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

确定