Go 字符串工具集的代码示范

43 min read

以下是 Go 字符串工具集的代码示范:

  1. 字符串切割
package main

import (
	"fmt"
	"strings"
)

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

	result := strings.Split(str, ", ")
	fmt.Println(result) // [Hello World!]
}
  1. 字符串替换
package main

import (
	"fmt"
	"strings"
)

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

	result := strings.Replace(str, "World", "Go", -1)
	fmt.Println(result) // Hello, Go!
}
  1. 字符串查找
package main

import (
	"fmt"
	"strings"
)

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

	result := strings.Contains(str, "World")
	fmt.Println(result) // true
}
  1. 字符串比较
package main

import (
	"fmt"
	"strings"
)

func main() {
	str1 := "Hello, World!"
	str2 := "HELLO, WORLD!"

	result := strings.EqualFold(str1, str2)
	fmt.Println(result) // true
}
  1. 字符串长度
package main

import (
	"fmt"
)

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

	result := len(str)
	fmt.Println(result) // 13
}