• Go 语言 strings 库常用方法


    最近由于用go做字符串处理,用到了go的strings库,借此对go strings库做个总结,将go strings中所有函数的功能做一个简单的说明,当然,这是一个重复造轮子的过程,因为go语言标准库已经有中文版了。

    🔗链接: Golang标准库文档

    strings

    package strings
    import “strings”

    strings包实现了用于操作字符的简单函数。

    函数列表

    func EqualFold

    func EqualFold(s, t string) bool
    
    • 1

    判断两个utf-8编码字符串(将unicode大写、小写、标题三种格式字符视为相同)是否相同。
    Example

    fmt.Println(strings.EqualFold("Go", "go"))
    
    • 1

    Output:

    true
    
    • 1

    func HasPrefix

    func HasPrefix(s, prefix string) bool
    
    • 1

    判断s是否有前缀字符串prefix。

    func HasSuffix

    func HasSuffix(s, suffix string) bool
    
    • 1

    判断s是否有后缀字符串suffix。

    func Contains

    func Contains(s, substr string) bool
    
    • 1

    判断字符串s是否包含子串substr。

    Example

    fmt.Println(strings.Contains("seafood", "foo"))
    fmt.Println(strings.Contains("seafood", "bar"))
    fmt.Println(strings.Contains("seafood", ""))
    fmt.Println(strings.Contains("", ""))
    
    • 1
    • 2
    • 3
    • 4

    Output:

    true
    false
    true
    true
    
    • 1
    • 2
    • 3
    • 4

    func ContainsRune

    func ContainsRune(s string, r rune) bool
    
    • 1

    判断字符串s是否包含utf-8码值r。

    func ContainsAny

    func ContainsAny(s, chars string) bool
    
    • 1

    判断字符串s是否包含字符串chars中的任一字符。
    Example

    fmt.Println(strings.ContainsAny("team", "i"))
    fmt.Println(strings.ContainsAny("failure", "u & i"))
    fmt.Println(strings.ContainsAny("foo", ""))
    fmt.Println(strings.ContainsAny("", ""))
    
    • 1
    • 2
    • 3
    • 4

    Output:

    false
    true
    false
    false
    
    • 1
    • 2
    • 3
    • 4

    func Count

    func Count(s, sep string) int
    
    • 1

    返回字符串s中有几个不重复的sep子串。

    Example

    fmt.Println(strings.Count("cheese", "e"))
    fmt.Println(strings.Count("five", "")) // before & after each rune
    
    • 1
    • 2

    Output:

    3
    5
    
    • 1
    • 2

    func Index

    func Index(s, sep string) int
    
    • 1

    子串sep在字符串s中第一次出现的位置,不存在则返回-1。

    func IndexByte

    func IndexByte(s string, c byte) int
    
    • 1

    字符c在s中第一次出现的位置,不存在则返回-1。

    func IndexRune

    func IndexRune(s string, r rune) int
    
    • 1

    unicode码值r在s中第一次出现的位置,不存在则返回-1。
    Example

    fmt.Println(strings.IndexRune("chicken", 'k'))
    fmt.Println(strings.IndexRune("chicken", 'd'))
    
    • 1
    • 2

    Output:

    4
    -1
    
    • 1
    • 2

    func IndexAny

    func IndexAny(s, chars string) int
    
    • 1

    字符串chars中的任一utf-8码值在s中第一次出现的位置,如果不存在或者chars为空字符串则返回-1。

    Example

    fmt.Println(strings.IndexAny("chicken", "aeiouy"))
    fmt.Println(strings.IndexAny("crwth", "aeiouy"))
    
    • 1
    • 2

    Output:

    2
    -1
    
    • 1
    • 2

    func IndexFunc

    func IndexFunc(s string, f func(rune) bool) int
    
    • 1

    s中第一个满足函数f的位置i(该处的utf-8码值r满足f®==true),不存在则返回-1。

    Example

    f := func(c rune) bool {
        return unicode.Is(unicode.Han, c)
    }
    fmt.Println(strings.IndexFunc("Hello, 世界", f))
    fmt.Println(strings.IndexFunc("Hello, world", f))
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Output:

    7
    -1
    
    • 1
    • 2

    func LastIndex

    func LastIndex(s, sep string) int
    
    • 1

    子串sep在字符串s中最后一次出现的位置,不存在则返回-1。

    Example

    fmt.Println(strings.Index("go gopher", "go"))
    fmt.Println(strings.LastIndex("go gopher", "go"))
    fmt.Println(strings.LastIndex("go gopher", "rodent"))
    
    • 1
    • 2
    • 3

    Output:

    0
    3
    -1
    
    • 1
    • 2
    • 3

    func LastIndexAny

    func LastIndexAny(s, chars string) int
    
    • 1

    字符串chars中的任一utf-8码值在s中最后一次出现的位置,如不存在或者chars为空字符串则返回-1。

    func LastIndexFunc

    func LastIndexFunc(s string, f func(rune) bool) int
    
    • 1

    s中最后一个满足函数f的unicode码值的位置i,不存在则返回-1。

    func Title

    func Title(s string) string
    
    • 1

    返回s中每个单词的首字母都改为标题格式的字符串拷贝。

    BUG: Title用于划分单词的规则不能很好的处理Unicode标点符号。

    Example

    fmt.Println(strings.Title("her royal highness"))
    
    • 1

    Output:

    Her Royal Highness
    
    • 1

    func ToLower

    func ToLower(s string) string
    
    • 1

    返回将所有字母都转为对应的小写版本的拷贝。
    Example

    fmt.Println(strings.ToLower("Gopher"))
    
    • 1

    Output:

    gopher
    
    • 1

    func ToLowerSpecial

    func ToLowerSpecial(_case unicode.SpecialCase, s string) string
    
    • 1

    使用_case规定的字符映射,返回将所有字母都转为对应的小写版本的拷贝。

    func ToUpper

    func ToUpper(s string) string
    
    • 1

    返回将所有字母都转为对应的大写版本的拷贝。
    Example

    fmt.Println(strings.ToUpper("Gopher"))
    
    • 1

    Output:

    GOPHER
    
    • 1

    func ToUpperSpecial

    func ToUpperSpecial(_case unicode.SpecialCase, s string) string
    
    • 1

    使用_case规定的字符映射,返回将所有字母都转为对应的大写版本的拷贝。

    func ToTitle

    func ToTitle(s string) string
    
    • 1

    返回将所有字母都转为对应的标题版本的拷贝。

    Example
    func ToTitleSpecial
    func ToTitleSpecial(_case unicode.SpecialCase, s string) string
    使用_case规定的字符映射,返回将所有字母都转为对应的标题版本的拷贝。

    func Repeat
    func Repeat(s string, count int) string
    返回count个s串联的字符串。

    Example

    fmt.Println(strings.ToTitle("loud noises"))
    fmt.Println(strings.ToTitle("хлеб"))
    
    • 1
    • 2

    Output:

    LOUD NOISES
    ХЛЕБ
    
    • 1
    • 2

    func Replace

    func Replace(s, old, new string, n int) string
    
    • 1

    返回将s中前n个不重叠old子串都替换为new的新字符串,如果n<0会替换所有old子串。

    Example

    fmt.Println("ba" + strings.Repeat("na", 2))
    
    • 1

    Output:

    banana
    
    • 1

    func Map

    func Map(mapping func(rune) rune, s string) string
    
    • 1

    将s的每一个unicode码值r都替换为mapping®,返回这些新码值组成的字符串拷贝。如果mapping返回一个负值,将会丢弃该码值而不会被替换。(返回值中对应位置将没有码值)

    Example

    rot13 := func(r rune) rune {
        switch {
        case r >= 'A' && r <= 'Z':
            return 'A' + (r-'A'+13)%26
        case r >= 'a' && r <= 'z':
            return 'a' + (r-'a'+13)%26
        }
        return r
    }
    fmt.Println(strings.Map(rot13, "'Twas brillig and the slithy gopher..."))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Output:

    'Gjnf oevyyvt naq gur fyvgul tbcure...
    
    • 1

    func Trim

    func Trim(s string, cutset string) string
    
    • 1

    返回将s前后端所有cutset包含的utf-8码值都去掉的字符串。

    Example

    fmt.Printf("[%q]", strings.Trim(" !!! Achtung! Achtung! !!! ", "! "))
    
    • 1

    Output:

    ["Achtung! Achtung"]
    
    • 1

    func TrimSpace

    func TrimSpace(s string) string
    
    • 1

    返回将s前后端所有空白(unicode.IsSpace指定)都去掉的字符串。

    Example

    fmt.Println(strings.TrimSpace(" \t\n a lone gopher \n\t\r\n"))
    
    • 1

    Output:

    a lone gopher
    
    • 1

    func TrimFunc

    func TrimFunc(s string, f func(rune) bool) string
    
    • 1

    返回将s前后端所有满足f的unicode码值都去掉的字符串。

    func TrimLeft

    func TrimLeft(s string, cutset string) string
    
    • 1

    返回将s前端所有cutset包含的utf-8码值都去掉的字符串。

    func TrimLeftFunc

    func TrimLeftFunc(s string, f func(rune) bool) string
    
    • 1

    返回将s前端所有满足f的unicode码值都去掉的字符串。

    func TrimPrefix

    func TrimPrefix(s, prefix string) string
    
    • 1

    返回去除s可能的前缀prefix的字符串。

    Example

    var s = "Goodbye,, world!"
    s = strings.TrimPrefix(s, "Goodbye,")
    s = strings.TrimPrefix(s, "Howdy,")
    fmt.Print("Hello" + s)
    
    • 1
    • 2
    • 3
    • 4

    Output:

    Hello, world!
    
    • 1

    func TrimRight

    func TrimRight(s string, cutset string) string
    
    • 1

    返回将s后端所有cutset包含的utf-8码值都去掉的字符串。

    func TrimRightFunc

    func TrimRightFunc(s string, f func(rune) bool) string
    
    • 1

    返回将s后端所有满足f的unicode码值都去掉的字符串。

    func TrimSuffix

    func TrimSuffix(s, suffix string) string
    
    • 1

    返回去除s可能的后缀suffix的字符串。

    Example

    var s = "Hello, goodbye, etc!"
    s = strings.TrimSuffix(s, "goodbye, etc!")
    s = strings.TrimSuffix(s, "planet")
    fmt.Print(s, "world!")
    
    • 1
    • 2
    • 3
    • 4

    Output:

    Hello, world!
    
    • 1

    func Fields

    func Fields(s string) []string
    
    • 1

    返回将字符串按照空白(unicode.IsSpace确定,可以是一到多个连续的空白字符)分割的多个字符串。如果字符串全部是空白或者是空字符串的话,会返回空切片。

    Example

    fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))
    
    • 1

    Output:

    Fields are: ["foo" "bar" "baz"]
    
    • 1

    func FieldsFunc

    func FieldsFunc(s string, f func(rune) bool) []string
    
    • 1

    类似Fields,但使用函数f来确定分割符(满足f的unicode码值)。如果字符串全部是分隔符或者是空字符串的话,会返回空切片。

    Example

    f := func(c rune) bool {
        return !unicode.IsLetter(c) && !unicode.IsNumber(c)
    }
    fmt.Printf("Fields are: %q", strings.FieldsFunc("  foo1;bar2,baz3...", f))
    
    • 1
    • 2
    • 3
    • 4

    Output:

    Fields are: ["foo1" "bar2" "baz3"]
    
    • 1

    func Split

    func Split(s, sep string) []string
    
    • 1

    用去掉s中出现的sep的方式进行分割,会分割到结尾,并返回生成的所有片段组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个字符串。

    Example

    fmt.Printf("%q\n", strings.Split("a,b,c", ","))
    fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
    fmt.Printf("%q\n", strings.Split(" xyz ", ""))
    fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
    
    • 1
    • 2
    • 3
    • 4

    Output:

    ["a" "b" "c"]
    ["" "man " "plan " "canal panama"]
    [" " "x" "y" "z" " "]
    [""]
    
    • 1
    • 2
    • 3
    • 4

    func SplitN

    func SplitN(s, sep string, n int) []string
    
    • 1

    用去掉s中出现的sep的方式进行分割,会分割到结尾,并返回生成的所有片段组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个字符串。参数n决定返回的切片的数目:

    n > 0 : 返回的切片最多n个子字符串;最后一个子字符串包含未进行切割的部分。
    n == 0: 返回nil
    n < 0 : 返回所有的子字符串组成的切片
    
    • 1
    • 2
    • 3

    Example

    fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 2))
    z := strings.SplitN("a,b,c", ",", 0)
    fmt.Printf("%q (nil = %v)\n", z, z == nil)
    
    • 1
    • 2
    • 3

    Output:

    ["a" "b,c"]
    [] (nil = true)
    
    • 1
    • 2

    func SplitAfter

    func SplitAfter(s, sep string) []string
    
    • 1

    用从s中出现的sep后面切断的方式进行分割,会分割到结尾,并返回生成的所有片段组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个字符串。

    Example

    fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ","))
    
    • 1

    Output:

    ["a," "b," "c"]
    
    • 1

    func SplitAfterN

    func SplitAfterN(s, sep string, n int) []string
    
    • 1

    用从s中出现的sep后面切断的方式进行分割,会分割到结尾,并返回生成的所有片段组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个字符串。参数n决定返回的切片的数目:

    n > 0 : 返回的切片最多n个子字符串;最后一个子字符串包含未进行切割的部分。
    n == 0: 返回nil
    n < 0 : 返回所有的子字符串组成的切
    
    • 1
    • 2
    • 3

    Example

    fmt.Printf("%q\n", strings.SplitAfterN("a,b,c", ",", 2))
    
    • 1

    Output:

    ["a," "b,c"]
    
    • 1

    func Join

    func Join(a []string, sep string) string
    
    • 1

    将一系列字符串连接为一个字符串,之间用sep来分隔。

    Example

    s := []string{"foo", "bar", "baz"}
    fmt.Println(strings.Join(s, ", "))
    
    • 1
    • 2

    Output:

    foo, bar, baz
    
    • 1

    type Reader

    type Reader struct {
        // 内含隐藏或非导出字段
    }
    
    • 1
    • 2
    • 3

    Reader类型通过从一个字符串读取数据,实现了io.Reader、io.Seeker、io.ReaderAt、io.WriterTo、io.ByteScanner、io.RuneScanner接口。

    func NewReader

    func NewReader(s string) *Reader
    
    • 1

    NewReader创建一个从s读取数据的Reader。本函数类似bytes.NewBufferString,但是更有效率,且为只读的。

    *func (Reader) Len

    func (r *Reader) Len() int
    
    • 1

    Len返回r包含的字符串还没有被读取的部分。

    *func (Reader) Read

    func (r *Reader) Read(b []byte) (n int, err error)
    
    • 1

    *func (Reader) ReadByte

    func (r *Reader) ReadByte() (b byte, err error)
    
    • 1

    *func (Reader) UnreadByte

    func (r *Reader) UnreadByte() error
    
    • 1

    *func (Reader) ReadRune

    func (r *Reader) ReadRune() (ch rune, size int, err error)
    
    • 1

    *func (Reader) UnreadRune

    func (r *Reader) UnreadRune() error
    
    • 1

    *func (Reader) Seek

    func (r *Reader) Seek(offset int64, whence int) (int64, error)
    
    • 1

    Seek实现了io.Seeker接口。

    *func (Reader) ReadAt

    func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)
    
    • 1

    *func (Reader) WriteTo

    func (r *Reader) WriteTo(w io.Writer) (n int64, err error)
    
    • 1

    WriteTo实现了io.WriterTo接口。

    type Replacer

    type Replacer struct {
        // 内含隐藏或非导出字段
    }
    
    • 1
    • 2
    • 3

    Replacer类型进行一系列字符串的替换。

    func NewReplacer

    func NewReplacer(oldnew ...string) *Replacer
    
    • 1

    使用提供的多组old、new字符串对创建并返回一个*Replacer。替换是依次进行的,匹配时不会重叠。

    Example

    r := strings.NewReplacer("<", "<", ">", ">")
    fmt.Println(r.Replace("This is HTML!"))
    
    • 1
    • 2

    Output:

    This is &lt;b&gt;HTML&lt;/b&gt;!
    
    • 1

    *func (Replacer) Replace

    func (r *Replacer) Replace(s string) string
    
    • 1

    Replace返回s的所有替换进行完后的拷贝。

    *func (Replacer) WriteString

    func (r *Replacer) WriteString(w io.Writer, s string) (n int, err error)
    
    • 1

    WriteString向w中写入s的所有替换进行完后的拷贝。

  • 相关阅读:
    middlebury立体匹配评估使用方法总结(二)——python版离线教程
    【线程池、有返回值的线程池、线程池监控】
    Spring Boot 日志文件
    Casein-PEG-Rhodamine B 络蛋白-聚乙二醇-罗丹明B Casein-RB
    手动与使用骨架创建Maven工程idea版及tomcat插件安装与web工程启动
    如何超越数据并行和模型并行:从GShard谈起
    QQ空间里面的照片变模糊了怎么办?时间越久越模糊怎么修复清晰?
    Unity拓展编辑器 找出未被引用的资源列表
    Flume学习笔记:03-自定义拦截器
    GO逃逸分析
  • 原文地址:https://blog.csdn.net/weixin_43064185/article/details/126173711