string 如何将多个字符串和 int 合并为一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35615839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to merge multiple strings and int into a single string
提问by Yi Jiang
I am a newbie in Go. I can't find any official docs showing how to merge multiple strings into a new string.
我是 Go 的新手。我找不到任何官方文档显示如何将多个字符串合并为一个新字符串。
What I'm expecting:
我期待的是:
Input: "key:"
, "value"
, ", key2:"
, 100
输入:"key:"
, "value"
, ", key2:"
,100
Output: "Key:value, key2:100"
输出:"Key:value, key2:100"
I want to use +
to merge strings like in Java and Swift if possible.
+
如果可能的话,我想使用像 Java 和 Swift 一样合并字符串。
回答by evanmcdonnal
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;
我喜欢用 fmt 的Sprintf
方法来处理这种类型的事情。它Printf
在 Go 或 C 中正常工作,只是它返回一个字符串。这是一个例子;
output := fmt.Sprintf("%s%s%s%d", "key:", "value", ", key2:", 100)
Go docs for fmt.Sprintf
转到fmt.Sprintf 的文档
回答by basgys
You can use strings.Join, which is almost 3x faster than fmt.Sprintf. However it can be less readable.
您可以使用strings.Join,它几乎比fmt.Sprintf 快3 倍。但是,它的可读性可能较差。
output := strings.Join([]string{"key:", "value", ", key2:", strconv.Itoa(100)}, "")
See https://play.golang.org/p/AqiLz3oRVq
见https://play.golang.org/p/AqiLz3oRVq
strings.Join vs fmt.Sprintf
strings.Join 与 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.
如果您需要合并很多字符串,我会考虑使用缓冲区而不是上面提到的那些解决方案。
回答by Sandeep Patel
You can simply do this:
你可以简单地这样做:
import (
"fmt"
"strconv"
)
func main() {
result:="str1"+"str2"+strconv.Itoa(123)+"str3"+strconv.Itoa(12)
fmt.Println(result)
}
Using fmt.Sprintf()
使用 fmt.Sprintf()
var s1="abc"
var s2="def"
var num =100
ans:=fmt.Sprintf("%s%d%s", s1,num,s2);
fmt.Println(ans);