Home > Backend Development > Golang > Golang string processing secrets: string variability and common operations

Golang string processing secrets: string variability and common operations

PHPz
Release: 2024-04-08 13:06:01
Original
1005 people have browsed it

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
}
Copy after login

实战案例

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()
Copy after login

字符串模板

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)
Copy after login

The above is the detailed content of Golang string processing secrets: string variability and common operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template