Skip to content

Go strings API

Go fmt 包 —— 使用 C 风格动词的格式化 I/O。

1 class · 10 methods

fmt

10 methods

fmt 包实现了格式化 I/O,其函数类似于 C 的 printf 和 scanf。

strings.Contains(s, substr string) bool

使用每个操作数的默认格式打印。当两个操作数都不是字符串时,会在操作数之间添加空格。

Parameters

NameTypeDescription
sstring要打印的操作数。
substrstringSubstring to find.

Returns

bool

Example

go
package main
import ("fmt"; "strings")
func main() {
    fmt.Println(strings.Contains("hello", "ell"))  // true
    fmt.Println(strings.Contains("hello", "xyz"))  // false
}
strings.HasPrefix(s, prefix string) bool

使用默认格式打印,操作数之间用空格分隔,末尾添加换行符。

Parameters

NameTypeDescription
sstring要打印的操作数。
prefixstringPrefix to test.

Returns

bool

Example

go
strings.HasPrefix("hello.go", "hello")  // true
strings.HasPrefix("hello.go", ".go")    // false
strings.HasSuffix(s, suffix string) bool

根据格式说明符打印。

Parameters

NameTypeDescription
formatstring格式字符串(例如 %v、%d、%s)。
suffixstring操作数。

Returns

bool

Example

go
strings.HasSuffix("hello.go", ".go")  // true
strings.HasSuffix("hello.go", "hello")  // false
strings.Index(s, substr string) int

根据格式说明符返回字符串(而非打印)。

Parameters

NameTypeDescription
formatstring格式字符串。
substrstring操作数。

Returns

int

Example

go
strings.Index("hello", "ll")  // 2
strings.Index("hello", "z")   // -1
strings.Split(s, sep string) []string

根据格式说明符写入 w。

Parameters

NameTypeDescription
sstring写入目标。
formatstring格式字符串。

Returns

[]string

Example

go
strings.Split("a,b,c", ",")  // ["a", "b", "c"]
strings.Split("hello", "")    // ["h","e","l","l","o"]
strings.Join(elems []string, sep string) string

扫描从标准输入读取的文本,将连续的以空格分隔的值依次存入连续的参数中。

Parameters

NameTypeDescription
format[]string格式字符串。
sepstring用于接收值的指针。

Returns

string

Example

go
strings.Join([]string{"a", "b", "c"}, "-")  // "a-b-c"
strings.Join([]string{"x"}, ",")            // "x"
strings.Replace(s, old, new string, n int) string

返回一个根据格式说明符格式化的错误。使用 %w 进行包装。

Parameters

NameTypeDescription
formatstring格式字符串(使用 %w 包装错误)。
oldstring操作数。
newstringReplacement.
nintMax replacements (-1 for all).

Returns

string

Example

go
strings.Replace("a-b-c", "-", "_", 1)   // "a_b-c"
strings.Replace("a-b-c", "-", "_", -1)  // "a_b_c"
strings.ToUpper(s string) string

Return s with all Unicode letters mapped to upper case.

Parameters

NameTypeDescription
sstringSource string.

Returns

string

Example

go
strings.ToUpper("hello")  // "HELLO"
strings.ToUpper("café")   // "CAFÉ"
strings.ToLower(s string) string

Return s with all Unicode letters mapped to lower case.

Parameters

NameTypeDescription
sstringSource string.

Returns

string

Example

go
strings.ToLower("HELLO")  // "hello"
strings.ToLower("CAFÉ")   // "café"
strings.Trim(s, cutset string) string

Return s with all leading and trailing characters in cutset removed.

Parameters

NameTypeDescription
sstringSource string.
cutsetstringCharacters to trim.

Returns

string

Example

go
strings.Trim("  hi  ", " ")   // "hi"
strings.Trim("xxhelloxx", "x")  // "hello"