go 語言中的字符串是不可變的,需要創(chuàng)建新字符串進(jìn)行修改。常用操作包括:字符串連接、長度獲取、比較、切片(取子字符串)、查找、替換、大小寫轉(zhuǎn)換、類型轉(zhuǎn)換。實(shí)戰(zhàn)案例中,演示了 url 解析和字符串模板的使用。
Go 字符串處理秘籍:可變性與常用操作
可變性
Go 中的字符串不可變,這意味著一旦創(chuàng)建一個(gè)字符串,就不能對其進(jìn)行修改。要修改字符串,需要創(chuàng)建一個(gè)新的字符串。
常用操作
以下是一些常用的字符串操作:
// 字符串連接
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)
// 字符串轉(zhuǎn)換大小寫
fmt.Println(strings.ToUpper("Hello, World!"))
fmt.Println(strings.ToLower("HELLO, WORLD!"))
// 字符串轉(zhuǎn)換為其他類型
number, err := strconv.Atoi("1234")
if err != nil {
// handle error
}
登錄后復(fù)制
實(shí)戰(zhàn)案例
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()
登錄后復(fù)制
字符串模板
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)
登錄后復(fù)制






