strings字符串函数
293字小于1分钟
2025-02-03
在Go里面可以利用字符串函数strings来对字符串数据进行一些常用的操作。
package main
import (
    "fmt"
    "strings"
)
func main() {
    // 字符串拼接
    str1 := "Hello,"
    str2 := "world!"
    // concatenated := str1 + " " + str2
    // concatenated = fmt.Sprintf("%s %s", str1, str2)
    concatenated := strings.Join([]string{str1, str2}, " ")
    fmt.Println("拼接后的字符串:", concatenated)
    // 字符串长度
    length := len(concatenated)
    fmt.Println("字符串长度:", length)
    // 字符串分割
    splitStr := "apple,banana,orange"
    pieces := strings.Split(splitStr, ",")
    fmt.Println("分割后的字符串切片:", pieces)
    // 字符串替换
    originalStr := "hello, world, world"
    replacedStr := strings.Replace(originalStr, "world", "golang", -1)
    fmt.Println("替换后的字符串:", replacedStr)
    // 字符串搜索
    searchStr := "hello"
    found := strings.Contains(originalStr, searchStr)
    fmt.Println("字符串是否包含'hello':", found)
    // 字符串前缀和后缀判断
    prefix := "hello"
    suffix := "world"
    isPrefix := strings.HasPrefix(originalStr, prefix)
    isSuffix := strings.HasSuffix(originalStr, suffix)
    fmt.Println("字符串是否以'hello'为前缀:", isPrefix)
    fmt.Println("字符串是否以'world'为后缀:", isSuffix)
    // 字符串大小写转换
    upperCase := strings.ToUpper(originalStr)
    lowerCase := strings.ToLower(originalStr)
    fmt.Println("转换为大写:", upperCase)
    fmt.Println("转换为小写:", lowerCase)
    // 字符串修剪
    trimStr := "   hello, world    "
    trimmed := strings.TrimSpace(trimStr)
    fmt.Println("修剪空格后的字符串:", trimmed)
    // 字符串重复
    repeated := strings.Repeat("hello", 3)
    fmt.Println("重复3次的字符串:", repeated)
}