strings

strings(标准库)包用于对字符串的处理,类似于python里面str类型的相关的方法

package main

import (
    "fmt"
    "strings"
)

func main() {

    s := "hello word!"                              // 定义一个字符串 
    slice := []string{"he", "ll", "ow", "or", "d"}  // 定义一个切片

    // 判断字符串前缀,返回bool值
    fmt.Println(strings.HasPrefix(s, "he"))     // 输出:True

    // 判断字符串后缀,返回bool值
    fmt.Println(strings.HasSuffix(s, "word!")) // 输出: True

    // 按照sep进行切割,返回slice
    fmt.Println(strings.Split(s, "e"))         // 输出:[h llo word!]

    // 判断是否包含子字符串,返回bool值
    fmt.Println(strings.Contains(s, "ell"))     // 输出:true

    // 字符串替换,后面的1代表要替换前1个,-1代表替换所有的,返回新的字符串
    fmt.Println(strings.Replace(s, "l", "L", 1))   // 输出:heLlo word!

    // 字符串出现的次数,返回int
    fmt.Println(strings.Count(s, "l"))          // 输出:2

    // 字符串重复次数,2表示重复2次, 返回新的字符串
    fmt.Println(strings.Repeat(s, 2))          // 输出:hello word!hello word!

    // 字符串大写转小写,返回新的字符串
    s := "Hello Word"                          // 输出: hello word
    fmt.Println(strings.ToLower(s))

    // 字符串小写转大写,返回新的字符串
    fmt.Println(strings.ToUpper(s))            // 输出:HELLO WORD!

    // 切换掉字符串的两边的空白字符,返回新的字符串
    s := " hello word "
    fmt.Println(strings.TrimSpace(s))         // 输出: hello word

    // 切掉左右两边指定的字符串,返回新的字符串
    fmt.Println(strings.Trim(s, "he"))         // 输出: llo word!

    // 切掉左边指定的字符串,返回新的字符串
    fmt.Println(strings.TrimLeft(s, "h"))      // 输出: ello word!

    // 切掉右边指定的字符串,返回新的字符串
    fmt.Println(strings.TrimRight(s, "d!"))     // 输出: hello wor

    // 字符串出现的次数,返回int
    fmt.Println(strings.Count(s, "l"))          // 输出:2

    // 使用指定分隔符将切片拼接组成一个字符串
    fmt.Println(strings.Join(slice, "|"))       // 输出: he|ll|ow|or|d

    // 字符串所在的索引位置,返回int,如果字符串不存在返回-1
    fmt.Println(strings.Index(s, "l"))         // 存在,输出索引2
    fmt.Println(strings.Index(s, "v"))         // 不存在,输出-1

    // 最后一个字符串的索引位置,返回int,如果不存在返回-1
    fmt.Println(strings.LastIndex(s, "o"))     // 输出7
}

 

posted @ 2018-09-23 14:25  opss  阅读(450)  评论(0)    收藏  举报