duanjihe5180
2016-02-25 00:14
采纳率: 100%
浏览 547
已采纳

如何将多个字符串和int合并为单个字符串

我是Go的新手。 找不到任何官方文档显示如何将多个字符串合并为一个新字符串。

我所期望的是:

输入值: "key:", "value", ", key2:", 100

输出值: "Key:value, key2:100"

如果可能的话,我想使用+来合并字符串,就像在Java和Swift中一样。

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

我是Go中的新手。 我找不到任何官方文档显示如何将多个字符串合并为一个新字符串。

我期望的是:

输入“ key:” ,< code>“值” “,key2:” 100

输出“键:值,键2:100”

如果可能,我想使用 + 来合并Java和Swift中的字符串

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

2条回答 默认 最新

  • dongtiannan0367 2016-02-25 00:19
    已采纳

    I like to use fmt's Sprintf method for this type of thing. It works like normal Printf in Go or C only it returns a string. Here's an example;

    output := fmt.Sprintf("%s%s%s%d", "key:", "value", ", key2:", 100)
    

    Go docs for fmt.Sprintf

    点赞 评论
  • doubipeng1336 2016-02-25 10:29

    You can use strings.Join, which is almost 3x faster than fmt.Sprintf. However it can be less readable.

    output := strings.Join([]string{"key:", "value", ", key2:", strconv.Itoa(100)}, "")
    

    See https://play.golang.org/p/AqiLz3oRVq

    strings.Join vs fmt.Sprintf

    BenchmarkFmt-4       2000000           685 ns/op
    BenchmarkJoins-4     5000000           244 ns/op
    

    Buffer

    If you need to merge a lot of strings, I'd consider using a buffer rather than those solutions mentioned above.

    点赞 评论

相关推荐 更多相似问题