英文:
Append key data from the GO MAP
问题
你可以使用循环遍历地将所有的键连接成一个以逗号分隔的字符串。以下是一个示例代码:
package main
import (
"fmt"
"strings"
)
func main() {
userinputmap := make(map[string]string)
userinputmap["key1"] = "value1"
userinputmap["key2"] = "value2"
userinputmap["key3"] = "value3"
keys := make([]string, 0, len(userinputmap))
for key := range userinputmap {
keys = append(keys, key)
}
output := strings.Join(keys, ",")
fmt.Println(output)
}
这段代码会输出:key1,key2,key3
。
英文:
I have a map in GO of the type :
var userinputmap = make(map[string]string)
The values in it are like :
userinputmap["key1"] = value1
userinputmap["key2"] = value2
userinputmap["key3"] = value3
How can I generate a string that contains al the above keys in comma seprated format?
output:= "key1,key2,key3"
答案1
得分: 7
在循环中迭代并将键添加到字符串中:
package main
import "fmt"
func main() {
var userinputmap = make(map[string]string)
userinputmap["key1"] = "value1"
userinputmap["key2"] = "value2"
userinputmap["key3"] = "value3"
output := ""
for key,_ := range userinputmap {
output += (key + ",")
}
output = output[:len(output)-1]
fmt.Println(output)
}
在循环中迭代并将键添加到字符串中。
英文:
iterate in a loop and append key to string:
package main
import "fmt"
func main() {
var userinputmap = make(map[string]string)
userinputmap["key1"] = "value1"
userinputmap["key2"] = "value2"
userinputmap["key3"] = "value3"
output :=""
for key,_ := range userinputmap {
output +=(key+",")
}
output = output[:len(output)-1]
fmt.Println(output)
}
答案2
得分: 2
另一种选择是将所有的键收集到一个切片中,然后使用strings.Join
方法将它们连接起来。
package main
import "fmt"
import "strings"
func main() {
var userinputmap = make(map[string]string)
userinputmap["key1"] = "value1"
userinputmap["key2"] = "value2"
userinputmap["key3"] = "value3"
keys := []string {}
for k, _ := range userinputmap {
keys = append(keys, k)
}
keys_string := strings.Join(keys, ",")
fmt.Println(keys_string)
}
请注意,这是一个Go语言的示例代码,用于将一个map中的键连接成一个字符串并打印出来。
英文:
Another option is to collect all your keys into a slice and then use strings.Join
method to join them.
package main
import "fmt"
import "strings"
func main() {
var userinputmap = make(map[string]string)
userinputmap["key1"] = "value1"
userinputmap["key2"] = "value2"
userinputmap["key3"] = "value3"
keys := []string {}
for k, _ := range userinputmap {
keys = append(keys, k)
}
keys_string := strings.Join(keys, ",")
fmt.Println(keys_string)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论