strings

strings

https://pkg.go.dev/strings@go1.20.1

​ strings包实现了一些简单的函数来操作 UTF-8 编码的字符串。

​ 有关 Go 中的 UTF-8 字符串的信息,请参阅 https://blog.golang.org/strings

常量

This section is empty.

变量

This section is empty.

函数

func Clone <- go1.18

1
func Clone(s string) string

​ Clone函数返回 s 的一个全新副本。它保证将 s 复制到一个新的分配中,当仅保留一个更大字符串的小子串时,这可能很重要。使用 Clone函数可以帮助这些程序使用更少的内存。当然,由于使用 Clone函数会进行复制,过度使用 Clone函数可能会使程序使用更多的内存。通常应仅在分析表明需要时才使用 Clone函数。对于长度为零的字符串,将返回字符串 “",并且不会进行任何分配。

func Compare <- go1.5

1
func Compare(a, b string) int

​ Compare函数按字典顺序比较两个字符串。

如果 a == b,则结果为 0;

如果 a < b,则结果为 -1;

如果 a > b,则结果为 +1。

​ Compare 函数只是为了与 bytes 包保持对称性而被包含进来的。使用内置的字符串比较运算符 ==、<、> 等通常更加清晰明了,而且速度更快。

Compare Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"strings"
)

func main() {
	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函数报告 substr 是否在 s 中。

Contains Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"fmt"
	"strings"
)

func main() {
	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 码点。

ContainsAny Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ContainsAny("team", "i"))
	fmt.Println(strings.ContainsAny("fail", "ui"))
	fmt.Println(strings.ContainsAny("ure", "ui"))
	fmt.Println(strings.ContainsAny("failure", "ui"))
	fmt.Println(strings.ContainsAny("foo", ""))
	fmt.Println(strings.ContainsAny("", ""))
}
Output:

false
true
true
true
false
false

func ContainsRune

1
func ContainsRune(s string, r rune) bool

​ ContainsRune函数报告 Unicode 码点 r 是否在 s 中。

ContainsRune Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"strings"
)

func main() {
	// 查找字符串是否包含特定的 Unicode 码点。
	// 例如,小写字母"a"的码点为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 是空字符串,则 Count 返回 s 中 Unicode 码点的数量加 1。

Count Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Count("cheese", "e"))
	fmt.Println(strings.Count("five", "")) // before & after each rune
}
Output:

3
5

func Cut <- go1.18

1
func Cut(s, sep string) (before, after string, found bool)

​ Cut函数围绕第一个 sep 实例对 s 进行切片,返回 sep 之前和之后的文本。found 结果报告 sep 是否出现在 s 中。如果 sep 不出现在 s 中,则 Cut 返回 s、""、false。

Cut Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
	"fmt"
	"strings"
)

func main() {
	show := func(s, sep string) {
		before, after, found := strings.Cut(s, sep)
		fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
	}
	show("Gopher", "Go")
	show("Gopher", "ph")
	show("Gopher", "er")
	show("Gopher", "Badger")
}
Output:

Cut("Gopher", "Go") = "", "pher", true
Cut("Gopher", "ph") = "Go", "er", true
Cut("Gopher", "er") = "Goph", "", true
Cut("Gopher", "Badger") = "Gopher", "", false

func CutPrefix <- go1.20

1
func CutPrefix(s, prefix string) (after string, found bool)

​ CutPrefix函数返回去掉前缀字符串 prefix 后的 s,并报告它是否找到了前缀。如果 s 不以 prefix 开头,则 CutPrefix函数返回 s、false。如果 prefix 是空字符串,则 CutPrefix 返回 s、true。

func CutSuffix <- go1.20

1
func CutSuffix(s, suffix string) (before string, found bool)

​ CutSuffix函数返回s中不包含指定结尾后缀字符串的部分,并报告它是否找到了后缀。如果s不以后缀结尾,则CutSuffix函数返回s,false。如果后缀为空字符串,则CutSuffix函数返回s,true。

func EqualFold

1
func EqualFold(s, t string) bool

​ EqualFold函数报告s和t在简单的Unicode折叠(一种更一般的不区分大小写的形式)下是否相等,这是一种更一般的不区分大小写的形式。

EqualFold Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.EqualFold("Go", "go"))
	fmt.Println(strings.EqualFold("AB", "ab")) // true because comparison uses simple case-folding
	fmt.Println(strings.EqualFold("ß", "ss"))  // false because comparison does not use full case-folding
}
Output:

true
true
false

func Fields

1
func Fields(s string) []string

​ Fields函数将字符串s按一个或多个连续的空格字符(由unicode.IsSpace定义)分割,返回s的子字符串切片或一个空切片,如果s仅包含空格,则返回空切片。

Fields Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	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函数将字符串s在每个运行满足f(c) 的Unicode码点c处分割,并返回s的切片数组。如果s中所有码点都满足f(c) 或字符串为空,则返回空切片。

​ FieldsFunc函数不保证调用f(c) 的顺序,并假定f始终为给定c返回相同的值。

FieldsFunc Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	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开头。

HasPrefix Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"fmt"
	"strings"
)

func main() {
	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 HasSuffix

1
func HasSuffix(s, suffix string) bool

​ HasSuffix函数测试字符串s是否以后缀suffix结尾。

HasSuffix Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.HasPrefix("Gopher", "Go"))
	fmt.Println(strings.HasPrefix("Gopher", "C"))
	fmt.Println(strings.HasPrefix("Gopher", ""))
}

Output:

true
false
true

func Index

1
func Index(s, substr string) int

​ Index函数返回substr在s中第一次出现的索引,如果substr不在s中,则返回-1。

Index Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
	"strings"
)

func main() {
	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中任何Unicode码点中chars的第一个实例的索引,如果s中不存在来自chars的Unicode码点,则返回-1。

IndexAny Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.IndexAny("chicken", "aeiouy"))
	fmt.Println(strings.IndexAny("crwth", "aeiouy"))
}
Output:

2
-1

func IndexByte <- go1.2

1
func IndexByte(s string, c byte) int

​ IndexByte函数返回c在s中第一次出现的索引,如果c不在s中,则返回-1。

IndexByte Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"strings"
)

func main() {
	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函数返回第一个满足f(c) 的Unicode码点c在s中的索引,如果没有则返回-1。

IndexFunc Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	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函数返回Unicode码点r在字符串s中第一次出现的索引,如果r不在s中,则返回-1。如果r是utf8.RuneError,则返回任何无效的UTF-8字节序列的第一个实例。

IndexRune Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.IndexRune("chicken", 'k'))
	fmt.Println(strings.IndexRune("chicken", 'd'))
}
Output:

4
-1

func Join

1
func Join(elems []string, sep string) string

​ Join函数将其第一个参数的元素连接起来以创建单个字符串。分隔符字符串sep放置在结果字符串中的元素之间。

Join Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := []string{"foo", "bar", "baz"}
	fmt.Println(strings.Join(s, ", "))
}
Output:

foo, bar, baz

func LastIndex

1
func LastIndex(s, substr string) int

​ LastIndexByte函数返回c在s中最后一次出现的索引,如果c不在s中,则返回-1。

LastIndex Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"strings"
)

func main() {
	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函数返回 chars 中任何 Unicode 码点在 s 中最后一次出现的索引,如果 s 中没有来自 chars 的 Unicode 码点,则返回 -1。

LastIndexAny Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"strings"
)

func main() {
	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 <- go1.5

1
func LastIndexByte(s string, c byte) int

​ LastIndexByte函数返回 c 在 s 中最后一次出现的索引,如果 c 不在 s 中,则返回 -1。

LastIndexByte Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"strings"
)

func main() {
	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函数返回最后一个满足 f(c) 的 Unicode 码点在 s 中的索引,如果没有,则返回-1。

LastIndexFunc Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	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 返回负值,则删除该字符而不替换。(例如返回-1

Map Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
	"fmt"
	"strings"
)

func main() {
	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函数返回由 count 个字符串 s 组成的新字符串。

​ 如果 count 为负数或 (len(s) * count) 的结果溢出,则会发生 panic。

Repeat Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	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个rune字符串提供最多k+1个替换。如果n < 0,则不限制替换次数。

Replace Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
	"strings"
)

func main() {
	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 ReplaceAll <- go1.12

1
func ReplaceAll(s, old, new string) string

​ ReplaceAll函数将字符串s中所有非重叠old实例替换为new,并返回新的字符串。如果old为空,则它匹配字符串开头和每个UTF-8序列之后,为k个rune字符串提供最多k+1个替换。

ReplaceAll Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ReplaceAll("oink oink oink", "oink", "moo"))
}
Output:

moo moo moo

func Split

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

​ Split函数将字符串s按sep分割成所有子字符串,并返回它们之间的子字符串切片。

​ 如果s不包含sep且sep不为空,则Split返回长度为1的切片,其中唯一的元素为s。

​ 如果sep为空,则Split在每个UTF-8序列之后拆分。如果s和sep都为空,则Split返回一个空切片。

​ 它等价于带有计数-1的SplitN函数。

​ 要在第一个分隔符实例周围分割,请参见Cut 函数

Split Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"fmt"
	"strings"
)

func main() {
	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函数将字符串s按sep分割成每个实例后的所有子字符串,并返回它们的子字符串切片。

​ 如果s不包含sep且sep不为空,则SplitAfter返回长度为1的切片,其中唯一的元素为s。

​ 如果sep为空,则SplitAfter在每个UTF-8序列之后拆分。如果s和sep都为空,则SplitAfter返回一个空切片。

​ 它等价于带有计数-1的SplitAfterN函数。

SplitAfter Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	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函数将字符串s按sep拆分为每个实例之后的子字符串,并返回它们的子字符串切片。

​ 计数参数n确定要返回的子字符串的数量:

n > 0:最多n个子字符串;最后一个子字符串将是未拆分的剩余部分。

n == 0:结果为nil(零个子字符串)

n < 0:所有子字符串

​ s和sep的边缘情况(例如,空字符串)的处理方式如SplitAfter函数文档中所述。

SplitAfterN Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	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

​ SplitN函数将字符串s按sep分割为每个分隔符之间的子字符串,并返回它们的子字符串切片。

​ 计数参数n确定要返回的子字符串的数量:

n > 0:最多n个子字符串;最后一个子字符串将是未拆分的剩余部分。

n == 0:结果为nil(零个子字符串)

n < 0:所有子字符串

​ 对于 s 和 sep 的边界情况(例如空字符串),将按照 Split函数文档中描述的方式处理。

​ 如果要在第一个分隔符周围进行分割,请参阅 Cut函数

SplitN Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
	"fmt"
	"strings"
)

func main() {
	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 ToLower

1
func ToLower(s string) string

​ ToLower函数返回s的所有Unicode字母均被映射为它们的小写形式的副本。

ToLower Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ToLower("Gopher"))
}
Output:

gopher

func ToLowerSpecial

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

​ ToLowerSpecial函数返回s的所有Unicode字母均被映射为它们的小写形式的副本,使用由c指定的大小写映射。

ToLowerSpecial Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	fmt.Println(strings.ToLowerSpecial(unicode.TurkishCase, "Önnek İş"))
}
Output:

önnek iş

func ToTitle

1
func ToTitle(s string) string

​ ToTitle函数返回s的所有Unicode字母均被映射为它们的Unicode标题形式的副本。

ToTitle Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
	"fmt"
	"strings"
)

func main() {
	// Compare this example to the Title example.
	fmt.Println(strings.ToTitle("her royal highness"))
	fmt.Println(strings.ToTitle("loud noises"))
	fmt.Println(strings.ToTitle("хлеб"))
}
Output:

HER ROYAL HIGHNESS
LOUD NOISES
ХЛЕБ

func ToTitleSpecial

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

​ ToTitleSpecial函数返回s的所有Unicode字母均被映射为它们的Unicode标题形式的副本,优先考虑特殊的大小写规则。

ToTitleSpecial Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	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字母均被映射为它们的大写形式的副本。

ToUpper Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ToUpper("Gopher"))
}
Output:

GOPHER

func ToUpperSpecial

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

​ ToUpperSpecial函数返回s的所有Unicode字母均被映射为它们的大写形式的副本,使用由c指定的大小写映射。

ToUpperSpecial Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	fmt.Println(strings.ToUpperSpecial(unicode.TurkishCase, "örnek iş"))
}
Output:

ÖRNEK İŞ

func ToValidUTF8 <- go1.13

1
func ToValidUTF8(s, replacement string) string

​ ToValidUTF8函数返回s的每个无效UTF-8字节序列的运行都被替换为替换字符串的副本,替换字符串可以为空。

func Trim

1
func Trim(s, cutset string) string

​ Trim函数返回字符串s的所有前导和尾随Unicode码点都包含在cutset中,这些码点被删除的切片。

Trim Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Print(strings.Trim("¡¡¡Hello, Gophers!!!", "!¡"))
}
Output:

Hello, Gophers

func TrimFunc

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

​ TrimFunc函数返回字符串 s 中所有符合函数 f 的 Unicode 码点的前缀和后缀都被删除后的子字符串。

TrimFunc Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	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, cutset string) string

​ TrimLeft函数返回字符串 s 去掉所有前导的包含在 cutset 中的 Unicode 码点后的子字符串。

​ 如果要去掉一个前缀,请使用 TrimPrefix函数。

TrimLeft Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Print(strings.TrimLeft("¡¡¡Hello, Gophers!!!", "!¡"))
}
Output:

Hello, Gophers!!!

func TrimLeftFunc

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

​ TrimLeftFunc函数返回字符串 s 去掉所有前导符合函数 f 的 Unicode 码点后的子字符串。

TrimLeftFunc Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
	"fmt"
	"strings"
	"unicode"
)

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

Hello, Gophers!!!

func TrimPrefix <- go1.1

1
func TrimPrefix(s, prefix string) string

​ TrimPrefix函数返回字符串 s 去掉提供的前缀字符串 prefix。如果 s 不以 prefix 开头,则返回 s 不变。

TrimPrefix Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
	"fmt"
	"strings"
)

func main() {
	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, cutset string) string

​ TrimRight函数返回字符串 s 去掉所有后缀的包含在 cutset 中的 Unicode 码点后的子字符串。

​ 如果要去掉一个后缀,请使用 TrimSuffix函数。

TrimRight Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Print(strings.TrimRight("¡¡¡Hello, Gophers!!!", "!¡"))
}
Output:

¡¡¡Hello, Gophers

func TrimRightFunc

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

​ TrimRightFunc函数返回字符串 s 去掉所有后缀符合函数 f 的 Unicode 码点后的子字符串。

TrimRightFunc Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	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 去掉所有前导和后缀的空白字符,根据 Unicode 定义。

TrimSpace Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}
Output:

Hello, Gophers

func TrimSuffix <- go1.1

1
func TrimSuffix(s, suffix string) string

​ TrimSuffix函数返回字符串 s 去掉提供的后缀字符串 suffix。如果 s 不以 suffix 结尾,则返回 s 不变。

TrimSuffix Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
	"fmt"
	"strings"
)

func main() {
	var s = "¡¡¡Hello, Gophers!!!"
	s = strings.TrimSuffix(s, ", Gophers!!!")
	s = strings.TrimSuffix(s, ", Marmots!!!")
	fmt.Print(s)
}
Output:

¡¡¡Hello

类型

type Builder <- go1.10

1
2
3
4
type Builder struct {
    addr *Builder // of receiver, to detect copies by value
	buf  []byte
}

​ Builder结构体用于使用 Write 方法高效地构建字符串。它最小化了内存复制。零值可直接使用。不要复制非零值 Builder。

Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"fmt"
	"strings"
)

func main() {
	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

(*Builder) Cap <- go1.12

1
func (b *Builder) Cap() int

​ Cap方法返回 builder 底层字节切片的容量。它是为正在构建的字符串分配的总空间,包括已经写入的任何字节。

(*Builder) Grow <- go1.10

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

​ Grow方法按需增加 b 的容量,以保证另外 n 个字节的空间。调用 Grow(n) 后,至少可以将 n 个字节写入 b,而不必另行分配。如果 n 为负数,则 Grow 会出现 panic。

(*Builder) Len <- go1.10

1
func (b *Builder) Len() int

​ Len方法返回已经累积的字节数;b.Len() == len(b.String())。

(*Builder) Reset <- go1.10

1
func (b *Builder) Reset()

​ Reset方法将 Builder 重置为空。

(*Builder) String <- go1.10

1
func (b *Builder) String() string

​ String方法返回已经累积的字符串。

(*Builder) Write <- go1.10

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

​ Write方法将 p 的内容追加到 b 的缓冲区中。Write 总是返回 len(p) 和 nil。

(*Builder) WriteByte <- go1.10

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

​ WriteByte方法将字节 c 追加到 b 的缓冲区中。返回的错误始终为 nil。

(*Builder) WriteRune <- go1.10

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

​ WriteRune方法将 Unicode 码点 r 的 UTF-8 编码附加到 b 的缓冲区中。它返回 r 的长度和 nil 错误。

(*Builder) WriteString <- go1.10

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

​ WriteString方法将字符串s的内容附加到b的缓冲区中。它返回s的长度和一个nil错误。

type Reader

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

​ Reader结构体通过从字符串中读取数据来实现io.Reader、io.ReaderAt、io.ByteReader、io.ByteScanner、io.RuneReader、io.RuneScanner、io.Seeker和io.WriterTo接口。Reader的零值像一个空字符串的Reader。

func NewReader

1
func NewReader(s string) *Reader

​ NewReader函数返回一个从s读取的新Reader。它类似于bytes.NewBufferString,但更高效且只读。

(*Reader) Len

1
func (r *Reader) Len() int

​ Len方法返回未读部分字符串的字节数。

(*Reader) Read

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

​ Read方法实现了io.Reader接口。

(*Reader) ReadAt

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

​ ReadAt方法实现了io.ReaderAt接口。

(*Reader) ReadByte

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

​ ReadByte方法实现了io.ByteReader接口。

(*Reader) ReadRune

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

​ ReadRune方法实现了io.RuneReader接口。

(*Reader) Reset <- go1.7

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

​ Reset方法将Reader重置为从s中读取。

(*Reader) Seek

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

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

(*Reader) Size <- go1.5

1
func (r *Reader) Size() int64

​ Size方法返回底层字符串的原始长度。Size方法是通过ReadAt方法可读取的字节数。返回值总是相同的,并不受任何其他方法的调用影响。

(*Reader) UnreadByte

1
func (r *Reader) UnreadByte() error

​ UnreadByte方法实现了 io.ByteScanner 接口。

(*Reader) UnreadRune

1
func (r *Reader) UnreadRune() error

​ UnreadRune方法实现了 io.RuneScanner 接口。

(*Reader) WriteTo <- go1.1

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

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

type Replacer

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

​ Replacer结构体可以用一组字符串替换另一组字符串。它可以被多个 goroutine 并发使用。

func NewReplacer

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

​ NewReplacer函数通过一组 old,new 字符串对返回一个新的 Replacer。替换按目标字符串中它们出现的顺序执行,而不会重叠匹配。old 字符串的比较按参数顺序执行。

​ 如果传入奇数个参数,NewReplacer函数将 panic。

NewReplacer Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
	"fmt"
	"strings"
)

func main() {
	r := strings.NewReplacer("<", "&lt;", ">", "&gt;")
	fmt.Println(r.Replace("This is <b>HTML</b>!"))
}
Output:

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

(*Replacer) Replace

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

​ Replace方法返回执行所有替换后的 s 的副本。

(*Replacer) WriteString

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

​ WriteString方法将 s 写入 w,执行所有替换。