Go语言教程之边写边学:Golang中的字符串:字符串操作

字符串连接

在Go中,可以使用运算符连接两个或多个字符串。

示例代码:

str1 := "Hello, "
str2 := "world!"
result := str1 + str2
fmt.Println(result) // Hello, world!

 

字符串切片

由于Go字符串是它们后面的字节切片,因此您可以像数组或切片一样处理字符串以获取字符串的子字符串。

示例代码:

str := "Hello, World!"
// 从下标7开始到11,不包含12
substring := str[7:12]
fmt.Println(substring) // Outputs: "World"

 

字符串搜索

您可以使用包中的字符串函数(如 Contains 等)轻松查找子字符串或字符。

示例代码:

package main

import (
  "fmt"
  "strings"
)

func main() {
  haystack := "Hello, Golang World!"


  needle := "Golang"


  if strings.Contains(haystack, needle) {
    fmt.Println("Found:", needle)
  } else {
    fmt.Println(needle, "not found!")
  }
}

 

字符串比较

Go提供了一种比较两个字符串是否相等的原生方法。此外,库Compare 中的函数字符串可用于确定两个字符串的字典顺序。

package main

import (
  "fmt"
)

func main() {
  str1 := "hello"
  str2 := "world"
  str3 := "hello"


  if str1 == str2 {
    fmt.Println("str1 and str2 are equal.")
  } else {
    fmt.Println("str1 and str2 are not equal.")
  }

  if str1 == str3 {
    fmt.Println("str1 and str3 are equal.")
  } else {
    fmt.Println("str1 and str3 are not equal.")
  }
}

输出:

str1 and str2 are not equal.
str1 and str3 are equal.

 

字符串替换

使用 ReplaceReplaceAll 函数,可以在Go中替换字符串中的子字符串。

package main

import (
  "fmt"
  "strings"
)

func main() {
  s := "banana"
  
  // 替换前两个'a' 和 'o'
  r1 := strings.Replace(s, "a", "o", 2)
  fmt.Println(r1) // "bonona"

  // 替换所有'a'和'o'
  r2 := strings.ReplaceAll(s, "a", "o")
  fmt.Println(r2) // "bonono"
}

 

字符串大小写转换

Go字符串库提供用于大小写转换的 ToUpperToLower 函数。

str := "GoLang"
lowercase := strings.ToLower(str)
uppercase := strings.ToUpper(str)
fmt.Println(lowercase)
fmt.Println(uppercase)

 

使用正则表达式处理字符串

Go正表达式库提供了一系列函数来使用正则表达式查询、匹配、替换和拆分字符串。

import "regexp"

str := "My email is example@example.com"
re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}`)
email := re.FindString(str)
fmt.Println(email) // example@example.com

 

字符串加密和哈希

Go的加密包提供了多种加密算法,可用于加密字符串或计算字符串的哈希值。

import (
    "crypto/md5"
    "fmt"
    "io"
)

str := "secret data"
hasher := md5.New()
io.WriteString(hasher, str)
fmt.Printf("%x\n", hasher.Sum(nil))

 

字符串拆分

使用字符串。拆分函数,可以通过指定的分隔符将字符串拆分为子字符串的切片。

str := "apple,banana,cherry"
items := strings.Split(str, ",")
fmt.Println(items)

 

字符串合并

字符串。Join 函数,将字符串切片组合成一个字符串。

items := []string{"apple", "banana", "cherry"}
str := strings.Join(items, ", ")
fmt.Println(str)

 

获取字符串中的字符

字符串中的每个字符都可以通过索引访问,但返回字符的字节值。

str := "Go"
byteValue := str[1]
fmt.Println(byteValue)

 

遍历字符串中的字符

使用for range 循环遍历字符串中的每个字符。

str := "Go"
for index, char := range str {
    fmt.Printf("At index %d, char: %c\n", index, char)
}

// At index 0, char: G
// At index 1, char: o

 

修剪字符串

字符串。TrimSpace 该函数可以删除字符串开头和结尾的空格。

str := "   Go Lang   "
trimmed := strings.TrimSpace(str)
fmt.Println(trimmed)

 

填充字符串

使用fmt包,您可以使用特定的格式修饰符填充或对齐字符串。

str := "Go"
padded := fmt.Sprintf("%-10s", str)
fmt.Println(padded)

 

字符串统计信息

count该函数可以帮助计算子字符串在字符串中出现的次数。

str := "Go is easy to learn. Go is powerful."
count := strings.Count(str, "Go")
fmt.Println(count)