英文:
How to convert key-value format string to map in golang?
问题
有一个格式化字符串如下:
"key1=value1&key2=value2"
如何将这个字符串优雅地转换为一个映射(map):
{"key1":"value1","key2":"value2"}
是否有像Guava的MapSplitter这样的好用工具?
英文:
There is a format string like this:
"key1=value1&key2=value2"
How to convert this string to a map elegantly:
{"key1":"value1","key2":"value2"}
Is there any good utils like Guava's MapSplitter?
答案1
得分: 2
你可以使用strings.Split()
函数两次来将整个字符串按照&
分割成key=value
对,然后再次使用=
将每个对分割成key
和value
。
快速示例代码(不处理边界情况):https://go.dev/play/p/t8oMbA72GCB
英文:
You can use strings.Split()
function twice to split the entire string into a key=value
pairs by &
and then again to split each pair to key
and value
by =
.
Quick playground without handling corner cases: https://go.dev/play/p/t8oMbA72GCB
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论