Z
ZHANK
复合类型

字符串与 rune

string 不可变 UTF-8、rune 遍历、strings 包、strconv 转换

字符串与 rune

Go 的 string 是不可变的 UTF-8 字节序列。遍历时用 rune 正确处理中文等多字节字符。

学完本章你将: 掌握 string 不可变性、rune 遍历、strings 包、strconv 转换。


字符串基础

go
package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "Hello, 世界"

    fmt.Println(len(s))     // 13(字节数,不是字符数!)
    fmt.Println(s[0])        // 72('H' 的 ASCII 码,byte 类型)
    // s[0] = 'h'            // ❌ string 不可变

    // 正确遍历 Unicode 字符
    for i, r := range s {
        fmt.Printf("%d: %c\n", i, r)
    }
    // 0: H, 1: e, ..., 7: 世, 10: 界
}

strings 包常用函数

go
import "strings"

s := "Hello World"

strings.Contains(s, "World")   // true
strings.HasPrefix(s, "He")     // true
strings.HasSuffix(s, "ld")     // true
strings.Index(s, "World")      // 6
strings.Replace(s, "World", "Go", 1)  // "Hello Go"
strings.Split("a,b,c", ",")    // ["a" "b" "c"]
strings.Join([]string{"a","b"}, ",")  // "a,b"
strings.ToUpper(s)             // "HELLO WORLD"
strings.TrimSpace("  hi  ")    // "hi"

strconv —— 字符串与数字互转

go
import "strconv"

// 字符串 → 数字
i, _ := strconv.Atoi("42")           // 42
f, _ := strconv.ParseFloat("3.14", 64) // 3.14

// 数字 → 字符串
s1 := strconv.Itoa(42)               // "42"
s2 := strconv.FormatFloat(3.14, 'f', 2, 64) // "3.14"
s3 := fmt.Sprintf("%d", 42)          // 灵活但稍慢