我是Go语言的新手。我找不到任何官方文档显示如何把多个字符串合并成一个新字符串。
我的期望:
输入:"key:"
,"value"
,", key2:"
,100
输出:"Key:value, key2:100"
如果可能的话,我想使用+
像Java和Swift那样合并字符串。
我喜欢使用 fmt 的 Sprintf
方法来处理这种类型的事情。它类似于 Go 或 C 中的 Printf
,但返回一个字符串。以下是一个示例:
output := fmt.Sprintf("%s%s%s%d", "key:", "value", ", key2:", 100)
查看 fmt.Sprintf 的 Go 文档。
output := strings.Join([]string{"key:", "value", ", key2:", strconv.Itoa(100)}, "")
请查看https://play.golang.org/p/AqiLz3oRVq
strings.Join 和 fmt.Sprintf 的区别
BenchmarkFmt-4 2000000 685 ns/op
BenchmarkJoins-4 5000000 244 ns/op
缓冲区
如果您需要合并大量字符串,建议使用缓冲区而不是上面提到的解决方案。
package main
import (
"fmt"
"strconv"
)
func main() {
result:="str1"+"str2"+strconv.Itoa(123)+"str3"+strconv.Itoa(12)
fmt.Println(result)
}
使用 fmt.Sprintf() 函数
var s1="abc"
var s2="def"
var num =100
ans:=fmt.Sprintf("%s%d%s", s1,num,s2);
fmt.Println(ans);
package main
import (
"fmt"
"io"
"os"
)
func main() {
const name, age = "John", 26
s := fmt.Sprintf("%s is %d years old.\n", name, age)
io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
}
输出:
约翰今年26岁。
您可以使用 text/template
:
package main
import (
"text/template"
"strings"
)
func format(s string, v interface{}) string {
t, b := new(template.Template), new(strings.Builder)
template.Must(t.Parse(s)).Execute(b, v)
return b.String()
}
func main() {
s := struct{
Key string
Key2 int
}{"value", 100}
f := format("key:{{.Key}}, key2:{{.Key2}}", s)
println(f)
}
或者使用fmt.Sprint
:
package main
import "fmt"
func main() {
s := fmt.Sprint("key:", "value", ", key2:", 100)
println(s)
}