字符串格式化输出
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
// 计算长度
sex := "tom"
fmt.Println(len(sex))
// 如果想计算中文长度,计算英文直接len()
name := "imoc你好世界"
bytes := []rune(name)
fmt.Println(len(bytes))
// 转义符
couseName01 := "go\"语言\""
couseName02 := `go"语言"`
fmt.Println(couseName01, couseName02)
// 格式输出
username := "bob"
age := 22
address := "北京"
mobile := "1999999999"
fmt.Println("用户名:" + username + ",年龄:" + strconv.Itoa(age) + ",地址:" + address + ", 电话:" + mobile) // 很难维护
fmt.Printf("用户名:%s, 年龄:%d, 地址:%s, 电话:%s\r\n", username, age, address, mobile) // 常用,但是性能不是很好
userMsg := fmt.Sprintf("用户名:%s, 年龄:%d, 地址:%s, 电话:%s", username, age, address, mobile)
fmt.Println(userMsg)
// 通过string的builder进行字符串拼接,高性能
var builder strings.Builder
builder.WriteString("用户名:")
builder.WriteString(username)
builder.WriteString(",年龄:")
builder.WriteString(strconv.Itoa(age))
builder.WriteString(",地址")
builder.WriteString(address)
builder.WriteString(",电话:")
builder.WriteString(mobile)
re := builder.String()
fmt.Println(re)
}
文章评论