Go 字符串的拼接方法和比较

8 min read
  1. 字符串的拼接方法

Go语言中,可以使用加号"+"来拼接字符串。例如:

str1 := "hello"
str2 := "world"
str3 := str1 + " " + str2
fmt.Println(str3) // 输出 "hello world"

另外,Go语言中还提供了 "fmt.Sprintf"、"strings.Join" 等方法来进行字符串拼接。

  • 使用 "fmt.Sprintf" 方法拼接字符串:
str1 := "hello"
str2 := "world"
str3 := fmt.Sprintf("%s %s", str1, str2)
fmt.Println(str3) // 输出 "hello world"
  • 使用 "strings.Join" 方法拼接字符串:
strList := []string{"hello", "world"}
str3 := strings.Join(strList, " ")
fmt.Println(str3) // 输出 "hello world"
  1. 字符串的比较

Go语言中,可以使用 "=="、"!="、">"、">="、"<"、"<=" 等运算符来比较字符串。

需要注意的是,Go语言中使用的是 Unicode 码点对字符串进行比较,而不是字典序。例如:

str1 := "hello"
str2 := "world"
fmt.Println(str1 < str2) // 输出 "true"

另外,还可以使用 "strings.Compare" 方法来比较字符串。该方法会按照字典序进行比较。

str1 := "hello"
str2 := "world"
res := strings.Compare(str1, str2)
fmt.Println(res) // 输出 "-1"

上面代码输出 "-1",表示 str1 < str2。如果 str1 == str2,则返回 0;如果 str1 > str2,则返回 1。