version: 1.10

package strings

import "strings"

概述

strings 包实现了一些操作 UTF-8 字符串的函数。

关于更多 Go 中的 UTF-8 字符串的信息,可以访问 https://blog.golang.org/strings.

索引

例子

文件

builder.go compare.go reader.go replace.go search.go strings.go strings_amd64.go strings_decl.go

func Compare


  1. func Compare(a, b string) int


Compare 根据字典顺序比较字符串 a 和 b。a == b 时返回 0,a < b 时返回 -1,a > b 时返回 +1。

Compare 主要为了和 bytes 包对应,通常使用内置的比较运算符(==,<,>)效率更高。


例:

fmt.Println(strings.Compare(“a”, “b”))
fmt.Println(strings.Compare(“a”, “a”))
fmt.Println(strings.Compare(“b”, “a”))
// Output:
// -1
// 0
// 1

func Contains


  1. func Contains(s, substr string) bool


Contains 判断 s 是否包含子串 substr。


例:

fmt.Println(strings.Contains(“seafood”, “foo”))
fmt.Println(strings.Contains(“seafood”, “bar”))
fmt.Println(strings.Contains(“seafood”, “”))
fmt.Println(strings.Contains(“”, “”))
// Output:
// true
// false
// true
// true

func ContainsAny


  1. func ContainsAny(s, chars string) bool


ContainsAny 判断 s 是否包含 chars 中的任意 Unicode 代码点Unicode code point


例:

fmt.Println(strings.ContainsAny(“team”, “i”))
fmt.Println(strings.ContainsAny(“failure”, “u & i”))
fmt.Println(strings.ContainsAny(“foo”, “”))
fmt.Println(strings.ContainsAny(“”, “”))
// Output:
// false
// true
// false
// false

func ContainsRune


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


ContainsRune 判断 s 是否包含 Unicode 代码点 r。


例:

// Finds whether a string contains a particular Unicode code point.
// The code point for the lowercase letter “a”, for example, is 97.
fmt.Println(strings.ContainsRune(“aardvark”, 97))
fmt.Println(strings.ContainsRune(“timeout”, 97))
// Output:
// true
// false

func Count


  1. func Count(s, substr string) int


Count 获取在 s 中非重叠出现 substr 的次数。如果 substr 为空,则返回 s 中的 Unicode 代码点数量加一。


例:

fmt.Println(strings.Count(“cheese”, “e”))
fmt.Println(strings.Count(“five”, “”)) // before & after each rune
// Output:
// 3
// 5

func EqualFold


  1. func EqualFold(s, t string) bool


EqualFold 判断 s 和 t 在忽略大小写的情况下是否相等。


例:

fmt.Println(strings.EqualFold(“Go”, “go”))
// Output: true

func Fields


  1. func Fields(s string) []string


Fields 根据空白字符(Go 中通过 unicode.IsSpace 判断是否为空白字符)分割字符串并将结果以切片形式返回。当 s 只包含空白字符时返回值为空。


例:

fmt.Printf(“Fields are: %q”, strings.Fields(“ foo bar baz “))
// Output: Fields are: [“foo” “bar” “baz”]

func FieldsFunc


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


FieldsFunc 根据满足函数 f(c) 的 Unicode 代码点 c 分割字符串。当 s 中所有的字符都满足 f(c) 函数或 s 为空时返回空。FieldsFunc 不保证 f(c) 的调用顺序,如果指定的 c 调用 f 返回结果不一致函数会崩溃。


例:

f := func(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
fmt.Printf(“Fields are: %q”, strings.FieldsFunc(“ foo1;bar2,baz3…”, f))
// Output: Fields are: [“foo1” “bar2” “baz3”]

func HasPrefix


  1. func HasPrefix(s, prefix string) bool


HasPrefix 判断 s 是否以 prefix 为前缀。


例:

fmt.Println(strings.HasPrefix(“Gopher”, “Go”))
fmt.Println(strings.HasPrefix(“Gopher”, “C”))
fmt.Println(strings.HasPrefix(“Gopher”, “”))
// Output:
// true
// false
// true

func HasSuffix


  1. func HasSuffix(s, suffix string) bool


HasSuffix 判断 s 是否以 suffix 为后缀。


例:

fmt.Println(strings.HasSuffix(“Amigo”, “go”))
fmt.Println(strings.HasSuffix(“Amigo”, “O”))
fmt.Println(strings.HasSuffix(“Amigo”, “Ami”))
fmt.Println(strings.HasSuffix(“Amigo”, “”))
// Output:
// true
// false
// false
// true

func Index


  1. func Index(s, substr string) int


Index 返回 s 中 substr 第一次出现的位置,如果没有返回 -1。


例:

fmt.Println(strings.Index(“chicken”, “ken”))
fmt.Println(strings.Index(“chicken”, “dmr”))
// Output:
// 4
// -1

func IndexAny


  1. func IndexAny(s, chars string) int


IndexAny 返回 s 中 chars 中任意 Unicode 代码点第一次出现的位置,如果没有返回 -1。


例:

fmt.Println(strings.IndexAny(“chicken”, “aeiouy”))
fmt.Println(strings.IndexAny(“crwth”, “aeiouy”))
// Output:
// 2
// -1

func IndexByte


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


IndexByte 返回 s 中 c 字节第一次出现的位置,如果没有返回 -1。


例:

fmt.Println(strings.IndexByte(“golang”, ‘g’))
fmt.Println(strings.IndexByte(“gophers”, ‘h’))
fmt.Println(strings.IndexByte(“golang”, ‘x’))
// Output:
// 0
// 3
// -1

func IndexFunc


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


IndexFunc 返回 s 中满足 f(c) 函数的 Unicode 代码点第一次出现的位置,如果没有返回 -1。


例:

f := func(c rune) bool {
return unicode.Is(unicode.Han, c)
}
fmt.Println(strings.IndexFunc(“Hello, 世界”, f))
fmt.Println(strings.IndexFunc(“Hello, world”, f))
// Output:
// 7
// -1

func IndexRune


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


IndexRune 返回 s 中 r 第一次出现的位置。如果没有返回 -1。当 r 是 utf8.RuneError 时返回无效 UTF-8 字节序列第一次出现的位置。


例:

fmt.Println(strings.IndexRune(“chicken”, ‘k’))
fmt.Println(strings.IndexRune(“chicken”, ‘d’))
// Output:
// 4
// -1

func Join


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


Join 将 a 中所有元素用 sep 连接并返回。


例:

s := []string{“foo”, “bar”, “baz”}
fmt.Println(strings.Join(s, “, “))
// Output: foo, bar, baz

func LastIndex


  1. func LastIndex(s, substr string) int


LastIndex 返回 s 中最后一次出现 sustr 时的位置,如果没有返回 -1。


例:

fmt.Println(strings.Index(“go gopher”, “go”))
fmt.Println(strings.LastIndex(“go gopher”, “go”))
fmt.Println(strings.LastIndex(“go gopher”, “rodent”))
// Output:
// 0
// 3
// -1

func LastIndexAny


  1. func LastIndexAny(s, chars string) int


LastIndexAny 返回 s 中最后一次出现 chars 中 Unicode 代码点时的位置,如果没有返回 -1。


例:

fmt.Println(strings.LastIndexAny(“go gopher”, “go”))
fmt.Println(strings.LastIndexAny(“go gopher”, “rodent”))
fmt.Println(strings.LastIndexAny(“go gopher”, “fail”))
// Output:
// 4
// 8
// -1

func LastIndexByte


  1. func LastIndexByte(s string, c byte) int


LastIndexByte 返回 s 中最后一次出现 c 字节时的位置,如果没有返回 -1。


例:

fmt.Println(strings.LastIndexByte(“Hello, world”, ‘l’))
fmt.Println(strings.LastIndexByte(“Hello, world”, ‘o’))
fmt.Println(strings.LastIndexByte(“Hello, world”, ‘x’))
// Output:
// 10
// 8
// -1

func LastIndexFunc


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


LastIndexFunc 返回 s 中最后一个满足 f(c) 函数的 Unicode 代码点的位置,如果没有返回 -1。


例:

fmt.Println(strings.LastIndexFunc(“go 123”, unicode.IsNumber))
fmt.Println(strings.LastIndexFunc(“123 go”, unicode.IsNumber))
fmt.Println(strings.LastIndexFunc(“go”, unicode.IsNumber))
// Output:
// 5
// 2
// -1

func Map


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


Map 为 s 中的每个字符应用回调函数 mapping 并返回处理结果。如果 mapping 返回一个负值该字符将会被丢弃。


例:

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…”))
// Output: ‘Gjnf oevyyvt naq gur fyvgul tbcure…

func Repeat


  1. func Repeat(s string, count int) string


Repeat 把 s 重复 count 次并返回结果。当 count 是负数或者 len(s) count 溢出函数会 panic。


例:

fmt.Println(“ba” + strings.Repeat(“na”, 2))
// Output: banana

func Replace


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


Replace 把 s 中的前 n 个非重叠的 old 替换为 new 并返回结果。如果 old 为空将会替换 UTF-8 代码点的前/后位置(例:长度为 k 的 UTF-8 字符串将被应用 k+1 次替换)。当 n < 0 时不会限制次数。


例:

fmt.Println(strings.Replace(“oink oink oink”, “k”, “ky”, 2))
fmt.Println(strings.Replace(“oink oink oink”, “oink”, “moo”, -1))
// Output:
// oinky oinky oink
// moo moo moo

func Split


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


Split 将 s 根据 sep 分割并以切片形式返回。

如果 s 中不包含 sep 并且 sep 不为空 Split 会把 s 作为切片元素返回(长度为 1)。

如果 sep 为空,将分割每个 UTF-8 字符。如果 s 和 sep 都为空 Split 会返回空切片。

Split 和 SplitN(-1) 是等价的。


例:

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”))
// Output:
// [“a” “b” “c”]
// [“” “man “ “plan “ “canal panama”]
// [“ “ “x” “y” “z” “ “]
// [“”]

func SplitAfter


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


SplitAfter 从每个 sep 后面分割 s 并以切片形式返回。

如果 s 中不包含 sep 并且 sep 不为空 SplitAfter 会把 s 作为切片元素返回(长度为 1)。

如果 sep 为空则分割每个 UTF-8 字符。如果 s 和 sep 都为空 SplitAfter 会返回空切片。

SplitAfter 和 SplitAfterN(-1) 是等价的。


例:

fmt.Printf(“%q\n”, strings.SplitAfter(“a,b,c”, “,”))
// Output: [“a,” “b,” “c”]

func SplitAfterN


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


SplitAfterN 从每个 sep 后面分割 s 并以切片形式返回。

参数 n 决定函数的返回值:

n > 0: 最多分割出 n 个子串; 最后一个子串不会再被分割
n == 0: 返回值为 nil
n < 0: 不限制分割后的子串数量

对于 s 和 sep 的边缘情况处理与 SplitAfter 相同。


例:

fmt.Printf(“%q\n”, strings.SplitAfterN(“a,b,c”, “,”, 2))
// Output: [“a,” “b,c”]

func SplitN


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


Split 将 s 根据 sep 分割并返回。

参数 n 决定函数的返回值:

n > 0: 最多分割出 n 个子串; 最后一个子串不会再被分割
n == 0: 返回值为 nil
n < 0: 不限制分割后的子串数量

对于 s 和 sep 的边缘情况处理与 Split 相同。


例:

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)
// Output:
// [“a” “b,c”]
// [] (nil = true)

func Title


  1. func Title(s string) string


Title 把 s 中每个单词的首字母转换成 Title 形式并返回。

BUG(rsc): Title 使用的判断字边界的规则会忽略 Unicode 标点符号。


例:

fmt.Println(strings.Title(“her royal highness”))
// Output: Her Royal Highness

func ToLower


  1. func ToLower(s string) string


ToLower 将 s 中的所有 Unicode 字符转换成小写。


例:

fmt.Println(strings.ToLower(“Gopher”))
// Output: gopher

func ToLowerSpecial


  1. func ToLowerSpecial(c unicode.SpecialCase, s string) string


ToLowerSpecial 根据 c 指定的优先规则将 s 中的所有 Unicode 代码点转换为小写。


例:

fmt.Println(strings.ToLowerSpecial(unicode.TurkishCase, “Önnek İş”))
// Output: önnek iş

func ToTitle


  1. func ToTitle(s string) string


ToTile 将 s 中的所有 Unicode 字符转换成 Title 形式。


例:

fmt.Println(strings.ToTitle(“loud noises”))
fmt.Println(strings.ToTitle(“хлеб”))
// Output:
// LOUD NOISES
// ХЛЕБ

func ToTitleSpecial


  1. func ToTitleSpecial(c unicode.SpecialCase, s string) string


ToTitleSpecial 根据 c 指定的优先规则将 s 中的所有 Unicode 代码点转换成 Title 形式。


例:

fmt.Println(strings.ToTitleSpecial(unicode.TurkishCase, “dünyanın ilk borsa yapısı Aizonai kabul edilir”))
// Output:
// DÜNYANIN İLK BORSA YAPISI AİZONAİ KABUL EDİLİR

func ToUpper


  1. func ToUpper(s string) string


ToUpper 将 s 中所有的 Unicode 字符转换成大写。


例:

fmt.Println(strings.ToUpper(“Gopher”))
// Output: GOPHER

func ToUpperSpecial


  1. func ToUpperSpecial(c unicode.SpecialCase, s string) string


ToUpperSpecial 根据 c 指定的优先规则将 s 中的所有字符转换成大写。


例:

fmt.Println(strings.ToUpperSpecial(unicode.TurkishCase, “örnek iş”))
// Output: ÖRNEK İŞ

func Trim


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


Trim 去掉 s 头部和尾部所有 cutset 中的 Unicode 代码点。


例:

fmt.Print(strings.Trim(“¡¡¡Hello, Gophers!!!”, “!¡”))
// Output: Hello, Gophers

func TrimFunc


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


TrimFunc 去掉 s 头部和尾部所有满足 f(c) 的 Unicode 代码点。


例:

fmt.Print(strings.TrimFunc(“¡¡¡Hello, Gophers!!!”, func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
}))
// Output: Hello, Gophers

func TrimLeft


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


TrimLeft 去掉 s 头部所有 cutset 中的 Unicode 代码点。


例:

fmt.Print(strings.TrimLeft(“¡¡¡Hello, Gophers!!!”, “!¡”))
// Output: Hello, Gophers!!!

func TrimLeftFunc


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


TrimLeftFunc 去掉 s 头部所有满足 f(c) 的 Unicode 代码点。


例:

fmt.Print(strings.TrimLeftFunc(“¡¡¡Hello, Gophers!!!”, func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
}))
// Output: Hello, Gophers!!!

func TrimPrefix


  1. func TrimPrefix(s, prefix string) string


TrimPrefix 去掉 s 的 prefix 前缀。如果 s 不以 prefix 作为前缀则直接返回。


例:

var s = “¡¡¡Hello, Gophers!!!”
s = strings.TrimPrefix(s, “¡¡¡Hello, “)
s = strings.TrimPrefix(s, “¡¡¡Howdy, “)
fmt.Print(s)
// Output: Gophers!!!

func TrimRight


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


TrimRignt 去掉 s 尾部所有 cutset 中的 Unicode 代码点。


例:

fmt.Print(strings.TrimRight(“¡¡¡Hello, Gophers!!!”, “!¡”))
// Output: ¡¡¡Hello, Gophers

func TrimRightFunc


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


TrimRightFunc 去掉字符串 s 尾部满足 f(c) 函数的 Unicode 代码点。


例:

fmt.Print(strings.TrimRightFunc(“¡¡¡Hello, Gophers!!!”, func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
}))
// Output: ¡¡¡Hello, Gophers

func TrimSpace


  1. func TrimSpace(s string) string


TrimSpace 去掉字符串 s 两边的空格。


例:

fmt.Println(strings.TrimSpace(“ \t\n Hello, Gophers \n\t\r\n”))
// Output: Hello, Gophers

func TrimSuffix


  1. func TrimSuffix(s, suffix string) string


TrimSuffix 去掉字符串 s 中的指定后缀 suffix。如果 s 不是以 suffix 结尾返回原字符串。


例:

var s = “¡¡¡Hello, Gophers!!!”
s = strings.TrimSuffix(s, “, Gophers!!!”)
s = strings.TrimSuffix(s, “, Marmots!!!”)
fmt.Print(s)
// Output: ¡¡¡Hello

type Builder


  1. type Builder struct {
    // contains filtered or unexported fields
    }


Builder 可以使用 Write 高效的创建字符串。他会把内存拷贝降到最低程度。可以直接使用 Builder 的零值。不要复制一个非零的 Builder。


例:

var b strings.Builder
for i := 3; i >= 1; i— {
fmt.Fprintf(&b, “%d…”, i)
}
b.WriteString(“ignition”)
fmt.Println(b.String())

// Output: 3…2…1…ignition

func (Builder) Grow


  1. func (b Builder) Grow(n int)


Grow 会增加 b 的容量确保他有足够的空间容纳 n 字节。在调用 Grow(n) 后,至少向 b 中写入 n 字节时不会重新分配内存。如果 n 为负数,Grow 会 panic。

func (Builder) Len


  1. func (b Builder) Len() int


Len 返回已经写入的字节;b.Len() == len(b.String())。

func (Builder) Reset


  1. func (b Builder) Reset()


Reset 将 Builder 重置为空。

func (Builder) String


  1. func (b Builder) String() string


String 返回已经写入的字符串。

func (Builder) Write


  1. func (b Builder) Write(p []byte) (int, error)


Write 会把 p 的内容追加到 b 的缓存中。Write 总是返回 len(p), nil。

func (Builder) WriteByte


  1. func (b Builder) WriteByte(c byte) error


WriteByte 将字节 c 追加到 b 的缓存中。返回的错误总是 nil。

func (Builder) WriteRune


  1. func (b Builder) WriteRune(r rune) (int, error)


WriteRune 将 UTF-8 编码的 Unicode 代码点 r 追加到 b 的缓存中。它返回 r 的长度和 nil 错误。

func (Builder) WriteString


  1. func (b Builder) WriteString(s string) (int, error)


WriteString 将 s 的内容追加到 b 的缓存中。它返回 s 的长度和 nil。

type Reader


  1. type Reader struct {
    // contains filtered or unexported fields
    }


Reader 实现对字符串读取的 io.Reader、io.ReaderAt、io.Seeker、io.WriterTo、io.ByteScanner 和 io.RuneScanner 接口。

func NewReader


  1. func NewReader(s string) Reader


NewReader 返回一个读取 s 的 Reader。它与 bytes.NewBufferString 类似不过 Reader 是只读的并且效率更高。

func (Reader) Len


  1. func (r Reader) Len() int


Len 返回字符串未读取部分的字节数。

func (Reader) Read


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



func (Reader) ReadAt


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



func (Reader) ReadByte


  1. func (r Reader) ReadByte() (byte, error)



func (Reader) ReadRune


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



func (Reader) Reset


  1. func (r Reader) Reset(s string)


Reset 使 Reader 开始读取 s。

func (Reader) Seek


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


Seek 方法实现了 io.Seeker 接口。

func (Reader) Size


  1. func (r Reader) Size() int64


Size 方法返回底层字符串的长度。它也是 ReadAt 能读取到的有效字节数。该返回值不受其他方法影响。

func (Reader) UnreadByte


  1. func (r Reader) UnreadByte() error



func (Reader) UnreadRune


  1. func (r Reader) UnreadRune() error



func (Reader) WriteTo


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


WriteTo 方法实现了 io.WriterTo 接口。

type Replacer


  1. type Replacer struct {
    // contains filtered or unexported fields
    }


Replacer 根据给定的替换列表来替换字符串。它可以安全的被多个 goroutine 同时使用。

func NewReplacer


  1. func NewReplacer(oldnew string) Replacer


NewReplacer 会配置 Replacer 的替换列表(每项都包含一个替换目标和替换值)并返回 Replacer。替换操作会按顺序进行并且不会重叠。


例:

r := strings.NewReplacer(“<”, “<”, “>”, “>”)
fmt.Println(r.Replace(“This is HTML!”))
// Output: This is <b>HTML</b>!

func (Replacer) Replace


  1. func (r Replacer) Replace(s string) string


Repalce 对 s 应用替换并返回替换结果。

func (Replacer) WriteString


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


WriteString 方法对 s 应用替换后将结果写入 w 中。

Bugs

  • Title 使用的判断字边界的规则会忽略 Unicode 标点符号。