Go 语言提供了一系列强大的字符串处理函数。这些函数主要集中在 strings
和 strconv
包中。下面是一些常用的字符串函数及其详解。
1. strings 包
1.1. Contains
检查字符串是否包含子串。
import ("fmt""strings"
)func main() {str = "hello world"fmt.Println(strings.Contains(str, "world")) // true
}
1.2. ContainsAny
检查字符串是否包含字符集中的任意一个字符。
import ("fmt""strings"
)func main() {fmt.Println(strings.ContainsAny("hello, world", "abc")) // falsefmt.Println(strings.ContainsAny("hello, world", "od")) // true
}
1.3. Count
计算子串在字符串中出现的次数。
import ("fmt""strings"
)func main() {fmt.Println(strings.Count("hello, hello, hello", "hello")) // 3
}
1.4. HasPrefix
检查字符串是否以指定前缀开头。
import ("fmt""strings"
)func main() {fmt.Println(strings.HasPrefix("hello, world", "hello")) // true
}
1.5. HasSuffix
检查字符串是否以指定后缀结尾。
import ("fmt""strings"
)func main() {fmt.Println(strings.HasSuffix("hello, world", "world")) // true
}
1.6. Index
返回子串在字符串中第一次出现的位置,不存在则返回 -1。
import ("fmt""strings"
)func main() {fmt.Println(strings.Index("hello, world", "world")) // 7
}
1.7. Join
连接字符串切片,使用指定的分隔符。
import ("fmt""strings"
)func main() {s := []string{"hello", "world"}fmt.Println(strings.Join(s, "&&&")) // "hello&&&world"
}
1.8. Repeat
重复字符串指定次数。
import ("fmt""strings"
)func main() {fmt.Println(strings.Repeat("a", 5)) // "aaaaa"
}
1.9. Replace
替换字符串中的子串。
import ("fmt""strings"
)func main() {fmt.Println(strings.Replace("hello, world", "world", "Go", 1)) // "hello, Go"
}
1.10. Split
使用指定的分隔符分割字符串,返回字符串切片。
import ("fmt""strings"
)func main() {fmt.Println(strings.Split("a,b,c", ",")) // ["a" "b" "c"]
}
1.11. Trim
去掉字符串两端的指定字符。
import ("fmt""strings"
)func main() {fmt.Println(strings.Trim("!!??!hello!!!", "!")) // "??!hello"
}
1.12. ToLower 和 ToUpper
转换字符串为小写或大写。
import ("fmt""strings"
)func main() {fmt.Println(strings.ToLower("HELLO")) // "hello"fmt.Println(strings.ToUpper("hello")) // "HELLO"
}
2. strconv 包
2.1. Atoi
将字符串转换为整数。
import ("fmt""strconv"
)func main() {i, err := strconv.Atoi("123")if err != nil {fmt.Println(err)} else {fmt.Println(i) // 123}
}
2.2. Itoa
将整数转换为字符串。
import ("fmt""strconv"
)func main() {s := strconv.Itoa(123)fmt.Println(s) // "123"
}
2.3. ParseFloat
将字符串转换为浮点数。
import ("fmt""strconv"
)func main() {f, err := strconv.ParseFloat("3.14", 64)if err != nil {fmt.Println(err)} else {fmt.Println(f) // 3.14}
}
2.4. FormatFloat
将浮点数转换为字符串。
import ("fmt""strconv"
)func main() {s := strconv.FormatFloat(3.14, 'f', 2, 64)fmt.Println(s) // "3.14"
}
2.5. ParseInt 和 FormatInt
将字符串转换为整数,或者将整数转换为字符串,支持不同进制。
import ("fmt""strconv"
)func main() {i, err := strconv.ParseInt("123", 10, 64)if err != nil {fmt.Println(err)} else {fmt.Println(i) // 123}s := strconv.FormatInt(123, 10)fmt.Println(s) // "123"
}
2.6. ParseBool 和 FormatBool
将字符串转换为布尔值,或者将布尔值转换为字符串。
import ("fmt""strconv"
)func main() {b, err := strconv.ParseBool("true")if err != nil {fmt.Println(err)} else {fmt.Println(b) // true}s := strconv.FormatBool(true)fmt.Println(s) // "true"
}
官方文档
string包
strconv包