package strings

import "strings"

Package strings 实现了用于操作 UTF-8 编码字符串的简单函数。

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

Index

Examples

Functions

func Clone

func Clone(s string) string

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

Example
package main

import (
	"fmt"
	"strings"
	"unsafe"
)

func main() {
	s := "abc"
	clone := strings.Clone(s)
	fmt.Println(s == clone)
	fmt.Println(unsafe.StringData(s) == unsafe.StringData(clone))
}

Output:

true
false

func Compare

func Compare(a, b string) int

Compare 返回一个按字典顺序比较两个字符串的整数。 如果 a == b,结果为 0;如果 a < b,结果为 -1;如果 a > b,结果为 +1。

当你需要执行三向比较时(例如与 slices.SortFunc 一起使用),请使用 Compare。 使用内置的字符串比较运算符 ==、<、> 等通常更清晰,而且总是更快。

Example
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

func Contains(s, substr string) bool

Contains 判断 substr 是否存在于 s 中。

Example
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

func ContainsAny(s, chars string) bool

ContainsAny 判断 chars 中任意 Unicode 码点是否存在于 s 中。

Example
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 ContainsFunc

func ContainsFunc(s string, f func(rune) bool) bool

ContainsFunc 判断 s 中是否存在任意 Unicode 码点 r 满足 f(r)。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	f := func(r rune) bool {
		return r == 'a' || r == 'e' || r == 'i' || r == 'o' || r == 'u'
	}
	fmt.Println(strings.ContainsFunc("hello", f))
	fmt.Println(strings.ContainsFunc("rhythms", f))
}

Output:

true
false

func ContainsRune

func ContainsRune(s string, r rune) bool

ContainsRune 判断 Unicode 码点 r 是否存在于 s 中。

Example
package main

import (
	"fmt"
	"strings"
)

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

func Count(s, substr string) int

Count 统计 substr 在 s 中非重叠出现的次数。 若 substr 为空字符串,Count 返回 1 + s 中 Unicode 码点的数量。

Example
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

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

Cut 围绕 sep 的首次出现位置切分 s, 返回 sep 前后的文本。 found 结果表示 sep 是否存在于 s 中。 若 sep 不存在于 s,cut 返回 s, "", false。

Example
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

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

CutPrefix 返回移除了指定前缀字符串的 s, 并报告是否找到该前缀。 若 s 不以 prefix 开头,CutPrefix 返回 s, false。 若 prefix 为空字符串,CutPrefix 返回 s, true。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	show := func(s, prefix string) {
		after, found := strings.CutPrefix(s, prefix)
		fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, prefix, after, found)
	}
	show("Gopher", "Go")
	show("Gopher", "ph")
}

Output:

CutPrefix("Gopher", "Go") = "pher", true
CutPrefix("Gopher", "ph") = "Gopher", false

func CutSuffix

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

CutSuffix 返回移除了指定后缀字符串的 s, 并报告是否找到该后缀。 若 s 不以 suffix 结尾,CutSuffix 返回 s, false。 若 suffix 为空字符串,CutSuffix 返回 s, true。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	show := func(s, suffix string) {
		before, found := strings.CutSuffix(s, suffix)
		fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, suffix, before, found)
	}
	show("Gopher", "Go")
	show("Gopher", "er")
}

Output:

CutSuffix("Gopher", "Go") = "Gopher", false
CutSuffix("Gopher", "er") = "Goph", true

func EqualFold

func EqualFold(s, t string) bool

EqualFold 判断 s 和 t(作为 UTF-8 字符串解析) 在简单 Unicode 大小写折叠规则下是否相等,这是一种更通用的不区分大小写比较方式。

Example
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

func Fields(s string) []string

Fields 以一个或多个连续空白字符(由 unicode.IsSpace 定义)为分隔符拆分字符串 s, 返回 s 的子字符串切片;若 s 仅包含空白字符则返回空切片。 返回切片的所有元素均非空。与 Split 不同,首尾连续的空白字符会被丢弃。

Example
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

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

FieldsFunc 以满足 f(c) 的连续 Unicode 码点为分隔符拆分字符串 s, 返回 s 的子切片数组。若 s 中所有码点均满足 f(c) 或字符串为空,则返回空切片。 返回切片的所有元素均非空。与 Split 不同,首尾满足 f(c) 的连续码点会被丢弃。

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

Example
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 FieldsFuncSeq

func FieldsFuncSeq(s string, f func(rune) bool) iter.Seq[string]

FieldsFuncSeq 返回一个迭代器,用于遍历围绕满足 f(c) 的 Unicode 码点序列分割的 s 的子字符串。 迭代器产生的字符串与 FieldsFunc 返回的字符串相同,但不会构建切片。

Example
package main

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

func main() {
	text := "The quick brown fox"
	fmt.Println("Split on whitespace(similar to FieldsSeq):")
	for word := range strings.FieldsFuncSeq(text, unicode.IsSpace) {
		fmt.Printf("%q\n", word)
	}

	mixedText := "abc123def456ghi"
	fmt.Println("\nSplit on digits:")
	for word := range strings.FieldsFuncSeq(mixedText, unicode.IsDigit) {
		fmt.Printf("%q\n", word)
	}

}

Output:

Split on whitespace(similar to FieldsSeq):
"The"
"quick"
"brown"
"fox"

Split on digits:
"abc"
"def"
"ghi"

func FieldsSeq

func FieldsSeq(s string) iter.Seq[string]

FieldsSeq 返回一个迭代器,用于遍历围绕由 unicode.IsSpace 定义的空白字符序列分割的 s 的子字符串。 迭代器产生的字符串与 Fields 返回的字符串相同,但不会构建切片。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "The quick brown fox"
	fmt.Println("Split string into fields:")
	for word := range strings.FieldsSeq(text) {
		fmt.Printf("%q\n", word)
	}

	textWithSpaces := "  lots   of   spaces  "
	fmt.Println("\nSplit string with multiple spaces:")
	for word := range strings.FieldsSeq(textWithSpaces) {
		fmt.Printf("%q\n", word)
	}

}

Output:

Split string into fields:
"The"
"quick"
"brown"
"fox"

Split string with multiple spaces:
"lots"
"of"
"spaces"

func HasPrefix

func HasPrefix(s, prefix string) bool

HasPrefix 判断字符串 s 是否以 prefix 开头。

Example
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 HasSuffix

func HasSuffix(s, suffix string) bool

HasSuffix 判断字符串 s 是否以 suffix 结尾。

Example
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 Index

func Index(s, substr string) int

Index 返回 substr 在 s 中第一次出现的索引,若不存在则返回 -1。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Index("chicken", "ken"))
	fmt.Println(strings.Index("chicken", "dmr"))
}

Output:

4
-1

func IndexAny

func IndexAny(s, chars string) int

IndexAny 返回 chars 中任意 Unicode 码点在 s 中第一次出现的索引, 若不存在则返回 -1。

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

2
-1

func IndexByte

func IndexByte(s string, c byte) int

IndexByte 返回 c 在 s 中第一次出现的索引,若不存在则返回 -1。

Example
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

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

IndexFunc 返回 s 中第一个满足 f(c) 的 Unicode 码点的索引, 若无则返回 -1。

Example
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

func IndexRune(s string, r rune) int

IndexRune 返回 Unicode 码点 r 在 s 中第一次出现的索引, 若不存在则返回 -1。 若 r 为 utf8.RuneError,则返回任意无效 UTF-8 字节序列的首次出现位置。

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

4
-1

func Join

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

Join 将第一个参数的元素拼接为单个字符串。 分隔符 sep 会被放置在结果字符串的元素之间。

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

foo, bar, baz

func LastIndex

func LastIndex(s, substr string) int

LastIndex 返回 substr 在 s 中最后一次出现的索引,若不存在则返回 -1。

Example
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

func LastIndexAny(s, chars string) int

LastIndexAny 返回 chars 中任意 Unicode 码点在 s 中最后一次出现的索引, 若不存在则返回 -1。

Example
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

func LastIndexByte(s string, c byte) int

LastIndexByte 返回 c 在 s 中最后一次出现的索引,若不存在则返回 -1。

Example
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

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

LastIndexFunc 返回 s 中最后一个满足 f(c) 的 Unicode 码点的索引, 若无则返回 -1。

Example
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 Lines

func Lines(s string) iter.Seq[string]

Lines 返回一个迭代器,用于遍历字符串 s 中以换行符结尾的行。 迭代器产生的行包含其结尾的换行符。 如果 s 为空,迭代器不会产生任何行。 如果 s 不以换行符结尾,则最后产生的行也不会以换行符结尾。 它返回一个单次使用的迭代器。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "Hello\nWorld\nGo Programming\n"
	for line := range strings.Lines(text) {
		fmt.Printf("%q\n", line)
	}

}

Output:

"Hello\n"
"World\n"
"Go Programming\n"

func Map

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

Map 返回字符串 s 的副本,其中所有字符根据映射函数进行修改。 若映射函数返回负值,则该字符会被从字符串中移除且无替换。

Example
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

func Repeat(s string, count int) string

Repeat 返回由字符串 s 重复 count 次组成的新字符串。

若 count 为负数,或 (len(s) * count) 结果溢出,该函数会触发 panic。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println("ba" + strings.Repeat("na", 2))
}

Output:

banana

func Replace

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

Replace 返回字符串 s 的副本,将前 n 个非重叠的 old 替换为 new。 若 old 为空,匹配字符串开头和每个 UTF-8 序列之后, 对于 k 个码点的字符串,最多进行 k+1 次替换。 若 n < 0,替换次数无限制。

Example
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

func ReplaceAll(s, old, new string) string

ReplaceAll 返回字符串 s 的副本,将所有非重叠的 old 替换为 new。 若 old 为空,匹配字符串开头和每个 UTF-8 序列之后, 对于 k 个码点的字符串,最多进行 k+1 次替换。

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

moo moo moo

func Split

func Split(s, sep string) []string

Split 将 s 按 sep 全量切分为子字符串,并返回分隔符之间的子字符串切片。

若 s 不包含 sep 且 sep 非空,Split 返回长度为 1 的切片,唯一元素为 s。

若 sep 为空,Split 在每个 UTF-8 序列后切分。 若 s 和 sep 均为空,Split 返回空切片。

该函数等价于 count 为 -1 的 SplitN

如需围绕分隔符的首次出现进行切分,请参阅 Cut

Example
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

func SplitAfter(s, sep string) []string

SplitAfter 在 sep 的每次出现位置后全量切分 s, 并返回这些子字符串的切片。

若 s 不包含 sep 且 sep 非空,SplitAfter 返回 长度为 1 的切片,唯一元素为 s。

若 sep 为空,SplitAfter 在每个 UTF-8 序列后切分。 若 s 和 sep 均为空,SplitAfter 返回空切片。

该函数等价于 count 为 -1 的 SplitAfterN

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ","))
}

Output:

["a," "b," "c"]

func SplitAfterN

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

SplitAfterN 在 sep 的每次出现位置后切分 s, 并返回这些子字符串的切片。

count 决定返回的子字符串数量:

s 和 sep 的边界情况(例如空字符串)处理方式 与 SplitAfter 文档中描述一致。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%q\n", strings.SplitAfterN("a,b,c", ",", 2))
}

Output:

["a," "b,c"]

func SplitAfterSeq

func SplitAfterSeq(s, sep string) iter.Seq[string]

SplitAfterSeq 返回一个迭代器,用于遍历在每个 sep 实例后分割的 s 的子字符串。 迭代器产生的字符串与 SplitAfter 返回的字符串相同,但不会构建切片。 它返回一个单次使用的迭代器。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "a,b,c,d"
	for part := range strings.SplitAfterSeq(s, ",") {
		fmt.Printf("%q\n", part)
	}

}

Output:

"a,"
"b,"
"c,"
"d"

func SplitN

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

SplitN 将 s 按 sep 切分为子字符串,并返回分隔符之间的子字符串切片。

count 决定返回的子字符串数量:

s 和 sep 的边界情况(例如空字符串)处理方式 与 Split 文档中描述一致。

如需围绕分隔符的首次出现进行切分,请参阅 Cut

Example
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 SplitSeq

func SplitSeq(s, sep string) iter.Seq[string]

SplitSeq 返回一个迭代器,用于遍历由 sep 分隔的 s 的所有子字符串。 迭代器产生的字符串与 Split 返回的字符串相同,但不会构建切片。 它返回一个单次使用的迭代器。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "a,b,c,d"
	for part := range strings.SplitSeq(s, ",") {
		fmt.Printf("%q\n", part)
	}

}

Output:

"a"
"b"
"c"
"d"

func Title

func Title(s string) string

Title 返回 s 的副本,其中所有单词开头的 Unicode 字母 均转换为 Unicode 标题大小写。

已弃用:Title 使用的单词边界规则无法正确处理 Unicode 标点符号。 请改用 golang.org/x/text/cases。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	// Compare this example to the ToTitle example.
	fmt.Println(strings.Title("her royal highness"))
	fmt.Println(strings.Title("loud noises"))
	fmt.Println(strings.Title("брат"))
}

Output:

Her Royal Highness
Loud Noises
Брат

func ToLower

func ToLower(s string) string

ToLower 返回 s 的副本,其中所有 Unicode 字母均转换为小写。

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

gopher

func ToLowerSpecial

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

ToLowerSpecial 返回 s 的副本,使用 c 指定的大小写映射规则 将所有 Unicode 字母转换为小写。

Example
package main

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

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

Output:

örnek iş

func ToTitle

func ToTitle(s string) string

ToTitle 返回 s 的副本,其中所有 Unicode 字母均转换为 Unicode 标题大小写。

Example
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

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

ToTitleSpecial 返回 s 的副本,将所有 Unicode 字母转换为 Unicode 标题大小写, 优先应用特殊大小写规则。

Example
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

func ToUpper(s string) string

ToUpper 返回 s 的副本,其中所有 Unicode 字母均转换为大写。

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

GOPHER

func ToUpperSpecial

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

ToUpperSpecial 返回 s 的副本,使用 c 指定的大小写映射规则 将所有 Unicode 字母转换为大写。

Example
package main

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

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

Output:

ÖRNEK İŞ

func ToValidUTF8

func ToValidUTF8(s, replacement string) string

ToValidUTF8 返回 s 的副本,其中每段无效 UTF-8 字节序列 均被替换为指定的替换字符串(替换字符串可为空)。

Example
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%s\n", strings.ToValidUTF8("abc", "\uFFFD"))
	fmt.Printf("%s\n", strings.ToValidUTF8("a\xffb\xC0\xAFc\xff", ""))
	fmt.Printf("%s\n", strings.ToValidUTF8("\xed\xa0\x80", "abc"))
}

Output:

abc
abc
abc

func Trim

func Trim(s, cutset string) string

Trim 返回字符串 s 的切片,移除所有开头和末尾包含在 cutset 中的 Unicode 码点。

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

Hello, Gophers

func TrimFunc

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

TrimFunc 返回字符串 s 的切片,移除所有开头和末尾满足 f(c) 的 Unicode 码点。

Example
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

func TrimLeft(s, cutset string) string

TrimLeft 返回字符串 s 的切片,移除所有开头包含在 cutset 中的 Unicode 码点。

如需移除前缀,请改用 TrimPrefix

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

Hello, Gophers!!!

func TrimLeftFunc

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

TrimLeftFunc 返回字符串 s 的切片,移除所有开头满足 f(c) 的 Unicode 码点。

Example
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

func TrimPrefix(s, prefix string) string

TrimPrefix 返回移除了指定前缀字符串的 s。 若 s 不以 prefix 开头,则原样返回 s。

Example
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

func TrimRight(s, cutset string) string

TrimRight 返回字符串 s 的切片,移除所有末尾包含在 cutset 中的 Unicode 码点。

如需移除后缀,请改用 TrimSuffix

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

¡¡¡Hello, Gophers

func TrimRightFunc

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

TrimRightFunc 返回字符串 s 的切片,移除所有末尾满足 f(c) 的 Unicode 码点。

Example
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

func TrimSpace(s string) string

TrimSpace 返回字符串 s 的切片(子字符串), 移除所有 Unicode 定义的首尾空白字符。

Example
package main

import (
	"fmt"
	"strings"
)

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

Output:

Hello, Gophers

func TrimSuffix

func TrimSuffix(s, suffix string) string

TrimSuffix 返回移除了指定后缀字符串的 s。 若 s 不以 suffix 结尾,则原样返回 s。

Example
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

Types

type Builder

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

Builder 用于通过 Builder.Write 方法高效地构建字符串。 它最大限度地减少了内存复制。零值即可使用。 不要复制非零的 Builder。

Example
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

func (*Builder) Cap

func (b *Builder) Cap() int

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

func (*Builder) Grow

func (b *Builder) Grow(n int)

Grow 如有必要,会增加 b 的容量,以确保有足够的空间再容纳 n 个字节。 在 Grow(n) 之后,至少可以向 b 写入 n 个字节而无需再次分配。如果 n 为负数,Grow 会引发 panic。

func (*Builder) Len

func (b *Builder) Len() int

Len 返回累积的字节数;b.Len() == len(b.String())。

func (*Builder) Reset

func (b *Builder) Reset()

Reset 将 Builder 重置为空。

func (*Builder) String

func (b *Builder) String() string

String 返回累积的字符串。

func (*Builder) Write

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

Write 将 p 的内容追加到 b 的缓冲区中。 Write 始终返回 len(p),nil。

func (*Builder) WriteByte

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

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

func (*Builder) WriteRune

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

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

func (*Builder) WriteString

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

WriteString 将 s 的内容追加到 b 的缓冲区中。 它返回 s 的长度和一个 nil 错误。

type Reader

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

Reader 通过读取字符串实现了 io.Readerio.ReaderAtio.ByteReaderio.ByteScannerio.RuneReaderio.RuneScannerio.Seeker 以及 io.WriterTo 接口。 Reader 的零值表现等同于读取空字符串的 Reader。

func NewReader

func NewReader(s string) *Reader

NewReader 返回一个从 s 读取数据的新 Reader。 它与 bytes.NewBufferString 功能相似,但效率更高且不可写入。

func (*Reader) Len

func (r *Reader) Len() int

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

func (*Reader) Read

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

Read 实现了 io.Reader 接口。

func (*Reader) ReadAt

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

ReadAt 实现了 io.ReaderAt 接口。

func (*Reader) ReadByte

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

ReadByte 实现了 io.ByteReader 接口。

func (*Reader) ReadRune

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

ReadRune 实现了 io.RuneReader 接口。

func (*Reader) Reset

func (r *Reader) Reset(s string)

Reset 将 Reader 重置为从 s 读取数据。

func (*Reader) Seek

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

Seek 实现了 io.Seeker 接口。

func (*Reader) Size

func (r *Reader) Size() int64

Size 返回底层字符串的原始长度。 Size 是可通过 Reader.ReadAt 读取的字节总数。 该返回值始终固定,不受其他任何方法调用的影响。

func (*Reader) UnreadByte

func (r *Reader) UnreadByte() error

UnreadByte 实现了 io.ByteScanner 接口。

func (*Reader) UnreadRune

func (r *Reader) UnreadRune() error

UnreadRune 实现了 io.RuneScanner 接口。

func (*Reader) WriteTo

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

WriteTo 实现了 io.WriterTo 接口。

type Replacer

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

Replacer 将一组字符串替换为对应的替换字符串。 它支持多个 goroutine 并发安全使用。

func NewReplacer

func NewReplacer(oldnew ...string) *Replacer

NewReplacer 从一组新旧字符串对返回一个新的 Replacer。 替换按照它们在目标字符串中出现的顺序执行,不进行重叠匹配。 旧字符串的比较按照参数顺序进行。

若传入奇数个参数,NewReplacer 会触发 panic。

Example
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;!

func (*Replacer) Replace

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

Replace 返回 s 的副本,其中所有替换均已执行。

func (*Replacer) WriteString

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

WriteString 将 s 写入 w,其中所有替换均已执行。