我想取一个字符串,并将其转换为map[string][]string. 到目前为止,我已经能够将字符串转换为 map[string]string,如下所示:package mainimport( "fmt" "strings")func main(){ var m map[string]string var ss []string s := "Owner.RefObjectName: Owner1, Owner2, Owner3&ScheduleState:State1, State2" ss = strings.Split(s, "&") m = make(map[string]string) for _, pair := range ss { z := strings.Split(pair, ":") m[z[0]] = z[1] } fmt.Println(m)}这给了我一个使用字符串键和字符串值的映射,如下所示:map[Owner.RefObjectName: Owner1, Owner2, Owner3 ScheduleState:State1, State2]但是,我需要将字符串值转换为字符串切片,因为我需要自己引用 Owner1 等各个项目。简而言之,我希望最终的地图看起来像这样:m := map[string][]string{ "Owner.RefObjectName": {"Owner1", "Owner2", "Owner3"}, "ScheduleState": {"State1", "State2"}, }其中 Owner1 Owner2 Owner3 不在单个字符串中,而是在字符串切片中。
1 回答
繁星淼淼
TA贡献1775条经验 获得超11个赞
用逗号进一步分割你的字符串:
var m map[string][]string
// ...
m = make(map[string][]string)
for _, pair := range ss {
obj := strings.Split(pair, ":")
key := obj[0]
v := strings.Split(obj[1], ",")
m[key] = v
}
- 1 回答
- 0 关注
- 210 浏览
添加回答
举报
0/150
提交
取消