在 Go 语言(Golang)中,字符串(string) 是一种基本数据类型,表示 UTF-8 编码的不可变字节序列。以下是字符串的基本特性和常见操作:
1.字符串的定义
Go 语言中的字符串使用双引号 "" 或反引号 ` ` 定义:
package main
import "fmt"
func main() {
var str1 string = "Hello, Go!" // 使用双引号
str2 := `Hello,
Go!` // 使用反引号(原始字符串,支持多行)
fmt.Println(str1)
fmt.Println(str2)
}
2.字符串的不可变性
Go 语言中的字符串是 不可变的,不能直接修改某个字符:
s := "hello"
// s[0] = 'H' // 错误,字符串不可变
如果需要修改,可以转换为 []byte 或 []rune:
s := "hello"
b := []byte(s) // 转换为字节切片
b[0] = 'H'
s = string(b) // 转换回字符串
fmt.Println(s) // "Hello"
3.字符串长度
- len(str) 计算字符串的 字节长度
- utf8.RuneCountInString(str) 计算 字符数
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
str := "你好Go!"
fmt.Println(len(str)) // 8(因为 "你好" 各占 3 字节)
fmt.Println(utf8.RuneCountInString(str)) // 4(真正的字符个数)
}
4.字符串遍历
可以使用 for 遍历字符串:
package main
import "fmt"
func main() {
s := "你好Go"
// 方式 1:按字节遍历
fmt.Println("按字节遍历:")
for i := 0; i < len(s); i++ {
fmt.Printf("%c ", s[i]) // 乱码,因为中文占 3 字节
}
fmt.Println()
// 方式 2:按字符(rune)遍历
fmt.Println("按字符遍历:")
for _, r := range s {
fmt.Printf("%c ", r) // 正确显示 "你 好 G o"
}
}
5.字符串拼接
使用+或fmt.Sprintf
s1 := "Hello"
s2 := "Go"
s3 := s1 + ", " + s2 + "!" // 方式 1
s4 := fmt.Sprintf("%s, %s!", s1, s2) // 方式 2
fmt.Println(s3, s4)
使用strings.Builder(高效拼接)
import "strings"
var builder strings.Builder
builder.WriteString("Hello")
builder.WriteString(", Go!")
fmt.Println(builder.String()) // "Hello, Go!"
6.字符串切割
import (
"fmt"
"strings"
)
func main() {
str := "apple,banana,orange"
parts := strings.Split(str, ",") // 按 "," 分割
fmt.Println(parts) // ["apple" "banana" "orange"]
}
7.字符串查找
import (
"fmt"
"strings"
)
func main() {
str := "hello, world"
fmt.Println(strings.Contains(str, "world")) // true
fmt.Println(strings.HasPrefix(str, "hello")) // true
fmt.Println(strings.HasSuffix(str, "world")) // true
fmt.Println(strings.Index(str, "world")) // 7
}
8.字符串替换
import (
"fmt"
"strings"
)
func main() {
str := "hello, world"
newStr := strings.Replace(str, "world", "Go", 1) // 只替换一次
fmt.Println(newStr) // "hello, Go"
}
9.字符串转换
import (
"fmt"
"strconv"
)
func main() {
// 数字转字符串
num := 123
str := strconv.Itoa(num) // "123"
// 字符串转数字
n, _ := strconv.Atoi("456") // 456
fmt.Println(str, n)
}
10.字符串与[]byte、[]rune转换
str := "你好"
b := []byte(str) // 转换为字节切片
r := []rune(str) // 转换为 Unicode 字符切片
fmt.Println(b) // [228 189 160 229 165 189]
fmt.Println(r) // [20320 22909]
总结
操作 | 方法 |
获取长度 | len(str)(字节数),utf8.RuneCountInString(str)(字符数) |
遍历字符串 | for i := 0; i < len(str); i++(按字节) |
拼接 | +,strings.Builder,fmt.Sprintf |
分割 | strings.Split(str, ",") |
查找 | strings.Contains,strings.Index,strings.HasPrefix,strings.HasSuffix |
替换 | strings.Replace |
转换 | strconv.Itoa(数字 → 字符串),strconv.Atoi(字符串 → 数字) |
string 与 []byte | []byte(str),string(b) |
string 与 []rune | []rune(str),string(r) |