go字符串操作

常用字符串操作使用的是strings包

字符串转换使用strconv包

1.字符串以xxx开始

strings.HasPrefix(url, startUrl) -- 判断字符串url是否以startUrl开头, 返回bool值

2.字符串以xxx结尾

strings.HasSuffix(path, endPath) -- 判断字符串path是否以endPath结尾

3.字符串替换

strings.Replace(str, "l", "a", 1) -- 将str中的l替换成a(这里只替换1次), 返回新替换后的字符串

此处替换后的结果是healo world, 如果想将str中的全部l替换成a, 则最后参数改为-1: trings.Replace(str, "l", "a", -1)

4.统计子串的个数

strings.Count("hello world", "l") -- 统计l出现的次数, 此处结果为3

5.重复字符串

strings.Repeat("hello world", 2) -- 将此字符串重复2次, 此处结果为:hello wordhello word

6.将字符串中的字符全部变小写

strings.ToLower("HEllo World") -- 结果为:hello world

7.将字符串中的字符全部变大写

strings.ToUpper("Hello Word") -- 结果为:HELLO WORD

8.去掉字符串中的首尾空白字符(空格符, 换行符, 制表符等)

strings.TrimSpace(" Hello world \n")  -- 结果为:Hello world(这里的空格和回车符都被去掉了)

9.Trim去掉首尾指定的字符

strings.Trim("!hello word!!!", "!") -- 结果为:hello word (多个相同的字符会当作一个字符对待, 如下也是:)

strings.Trim("abc bcababababababaxxxxxaabb", "ab") -- 结果为:c bcababababababaxxxxx

10.TrimLeft去掉开头的指定字符(和上面类似)

strings.TrimLeft("hhello world he", "he") -- 结果为:llo world he

11.TrimRight去掉结尾的指定字符(和上面类似)

12.字符串分隔(以空白分隔, 不仅仅是空格)

fields := strings.Fields(" hello      word \n ok")  -- 返回切片

for i:= 0; i<len(fields); i++ {                           

     fmt.Println(fields[i])                // 此处结果为:[hello word ok] 

}

13.指定符号分隔字符串

strings.Split("hello world", "ll") -- 以ll分隔此字符串, 返回切片, 此处结果为:[he o world]

14.字符串连接(将切片中的元素连接成一个字符串)

split := strings.Split("hello world", " ")      // [hello world]

joinStr := strings.Join(split, "+")              // hello+world

15.将string转成int型(不能成功转换, 则报error)

convertToInt, err := strconv.Atoi("123")

if err != nil {

    fmt.Println("不能转换")

}

fmt.Println(convertToInt)     // 123

16.将int型转成string

strconv.Itoa(123)      // 123

17.子串第一次出现的位置(如果没有则返回-1)

strings.Index("hello world", "world")  -- 结果为:6

猜你喜欢

转载自blog.csdn.net/lljxk2008/article/details/86660874