首页 > 文章列表 > Golang 字符串处理秘籍:字符串的可变性与常用操作

Golang 字符串处理秘籍:字符串的可变性与常用操作

字符串 golang
477 2024-04-23

Go 语言中的字符串是不可变的,需要创建新字符串进行修改。常用操作包括:字符串连接、长度获取、比较、切片(取子字符串)、查找、替换、大小写转换、类型转换。实战案例中,演示了 URL 解析和字符串模板的使用。

Golang 字符串处理秘籍:字符串的可变性与常用操作

Go 字符串处理秘籍:可变性与常用操作

可变性

Go 中的字符串不可变,这意味着一旦创建一个字符串,就不能对其进行修改。要修改字符串,需要创建一个新的字符串。

常用操作

以下是一些常用的字符串操作:

// 字符串连接
result := "Hello" + ", " + "World!"

// 字符串长度
fmt.Println("Hello, World!".Len())

// 字符串比较
fmt.Println("Hello, World!" == "Hello, World!")

// 字符串切片(取子字符串)
fmt.Println("Hello, World!"[1:7])

// 字符串查找
index := strings.Index("Hello, World!", "World")
fmt.Println(index)

// 字符串替换
result := strings.Replace("Hello, World!", "World", "Go", 1)

// 字符串转换大小写
fmt.Println(strings.ToUpper("Hello, World!"))
fmt.Println(strings.ToLower("HELLO, WORLD!"))

// 字符串转换为其他类型
number, err := strconv.Atoi("1234")
if err != nil {
    // handle error
}

实战案例

URL 解析

import "net/url"

url, err := url.Parse("https://example.com/paths/name?q=param")
if err != nil {
    // handle error
}

path := url.Path
query := url.Query()

result := path + "?" + query.Encode()

字符串模板

import "text/template"

const templateSource = "{{.Name}} is {{.Age}} years old."

tmpl, err := template.New("template").Parse(templateSource)
if err != nil {
    // handle error
}

data := struct{
    Name string
    Age   int
}

tmpl.Execute(os.Stdout, data)