首页 > 其他 > 详细

Golang - 处理字符串

时间:2019-04-14 10:44:22      阅读:105      评论:0      收藏:0      [点我收藏+]

Golang - 处理字符串

1. 字符串操作

func Contains(s, substr string) bool
字符串s中是否包含substr,返回bool值

func main() {
   fmt.Println(strings.Contains("hello", "llo"))
}

func Join(a []string, sep string) string
- 字符串链接,把slice a通过sep链接起来

func main() {
   s := []string{"abc", "456", "999"}
   fmt.Println(strings.Join(s, "** "))
}

func Index(s, sep string) int
在字符串s中查找sep所在的位置,返回位置值,找不到返回-1

func main() {
   fmt.Println(strings.Index("chicken", "ken"))
}

func Repeat(s string, count int) string
重复s字符串count次,最后返回重复的字符串

func main() {
   fmt.Println("ba" + strings.Repeat("na", 2))
}

func Replace(s, old, new string, n int) string
在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换

func main() {
   fmt.Println(strings.Replace("ok ok ok", "k", "ky", 2))
}

func Split(s, sep string) []string
把s字符串按照sep分割,返回slice

func main() {
   fmt.Printf("%q\n", strings.Split("a,b,c", ","))
}

func Trim(s string, cutset string) string
在s字符串的头部和尾部去除cutset指定的字符串

func main() {
   fmt.Printf("[%q]", strings.Trim(" !哈!哈! ", "! "))
}

func Fields(s string) []string
去除s字符串的空格符,并且按照空格分割返回slice

func main() {
   fmt.Println( strings.Fields("  a b  c   "))
}

2. 字符串转换

  • Append系列函数:将整数等转换为字符串后,添加到现有的字节数组中
  • Format系列函数:把其他类型的转换为字符串
  • Parse系列函数:把字符串转换为其他类型

Golang - 处理字符串

原文:https://www.cnblogs.com/konghui/p/10703608.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!