Goaddstring教程展示了如何在Golang中连接字符串。
在Go中,字符串是字节的只读切片。
在Go中有几种添加字符串的方法:
- +和+=运算符
- strings.Join方法
- 字符串格式化
- strings.Builder
- 字节。缓冲区
- 附加到字节片
$ go version go version go1.18.1 linux/amd64
我们使用Go版本1.18。
使用+运算符添加字符串
+和+=运算符提供了连接字符串的最简单方法。+运算符用于添加数字和字符串;在编程中我们说运算符重载。
package main
import "fmt"
func main() {
w1 := "an"
w2 := " old"
w3 := " falcon"
msg := w1 + w2 + w3
fmt.Println(msg)
}
两个字符串用+运算符相加。
$ go run addoper.go an old falcon
在第二个例子中,我们使用复合加法运算符。
package main
import "fmt"
func main() {
msg := "There are"
msg += " three falcons"
msg += " in the sky"
fmt.Println(msg)
}
该示例使用+=运算符构建一条消息。
$ go run addoper2.go There are three falcons in the sky
用strings.Join去添加字符串
string.Join方法连接切片的元素以创建单个字符串。第二个参数是放置在结果字符串中元素之间的分隔符。
package main
import (
"fmt"
"strings"
)
func main() {
s := []string{"There", "are", "two", "owls", "on", "the", "tree", "\n"}
fmt.Printf(strings.Join(s, " "))
}
在代码示例中,我们通过连接多个单词来形成一条消息。这些词是用一个空格字符连接的。
$ go run joining.go There are two owls on the tree
使用字符串格式添加字符串
字符串可以与Go的字符串格式化函数连接:fmt.Sprint、fmt.Sprintln和fmt.Sprintf。
package main
import "fmt"
func main() {
w1 := "an"
w2 := "old"
w3 := "falcon"
msg := fmt.Sprintf("%s %s %s", w1, w2, w3)
fmt.Println(msg)
}
我们使用fmt.Sprintf函数连接三个单词。
$ go run string_format.go an old falcon
去用strings.Builder添加字符串
strings.Builder用于使用Write方法高效地构建字符串。
package main
import (
"fmt"
"strings"
)
func main() {
var builder strings.Builder
builder.WriteString("There")
builder.WriteString(" are")
builder.WriteString(" two")
builder.WriteString(" falcons")
builder.WriteString(" in")
builder.WriteString(" the")
builder.WriteString(" sky")
fmt.Println(builder.String())
}
该示例使用strings.Builder构建字符串
builder.WriteString("There")
使用WriteString添加了一个新字符串。
fmt.Println(builder.String())
String返回累积的字符串。
去用bytes.Buffer添加字符串
Buffer是可变大小的字节缓冲区,具有读取和写入方法。
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
buffer.WriteString("a")
buffer.WriteString(" beautiful")
buffer.WriteString(" day")
fmt.Println(buffer.String())
}
WriteString方法将给定字符串的内容附加到缓冲区,根据需要增大缓冲区。
fmt.Println(buffer.String())
String方法将缓冲区未读部分的内容作为字符串返回。
用字节切片添加字符串
以下示例使用字节切片连接字符串。
package main
import (
"fmt"
)
func main() {
var s1 = "an"
var s2 = " old"
var s3 = " falcon"
msg := make([]byte, 0)
msg = append(msg, []byte(s1)...)
msg = append(msg, []byte(s2)...)
msg = append(msg, []byte(s3)...)
fmt.Println(string(msg))
}
该示例添加了三个字符串。
msg := make([]byte, 0)
使用make函数创建一个新的字节片。
msg = append(msg, []byte(s1)...)
我们使用byte将字符串转换为字节切片,并使用append将其附加到msg切片。
fmt.Println(string(msg))
最后,我们使用string将字节切片转换为字符串。
在本教程中,我们展示了如何在Golang中添加字符串。
列出所有Go教程。
