strings

Package strings implements simple functions to manipulate UTF-8 encoded strings.

Index

Functions

func Contains

1func Contains(s, substr string) bool

Contains reports whether substr is within s.

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

Output

true
false
true
true

func ContainsAny

1func ContainsAny(s, chars string) bool

ContainsAny reports whether any Unicode code points in chars are within s.

1fmt.Println(strings.ContainsAny("team", "i"))
2fmt.Println(strings.ContainsAny("fail", "ui"))
3fmt.Println(strings.ContainsAny("ure", "ui"))
4fmt.Println(strings.ContainsAny("failure", "ui"))
5fmt.Println(strings.ContainsAny("foo", ""))
6fmt.Println(strings.ContainsAny("", ""))

Output

false
true
true
true
false
false

func ContainsRune

1func ContainsRune(s string, r rune) bool

ContainsRune reports whether the Unicode code point r is within s.

1fmt.Println(strings.ContainsRune("aardvark", 97))
2fmt.Println(strings.ContainsRune("timeout", 97))

Output

true
false

func Count

1func Count(s, substr string) int

Count counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s.

1fmt.Println(strings.Count("cheese", "e"))
2fmt.Println(strings.Count("five", ""))

Output

3
5

func EqualFold

1func EqualFold(s, t string) bool

EqualFold reports whether s and t, interpreted as UTF-8 strings, are equal under simple Unicode case-folding, which is a more general form of case-insensitivity.

1fmt.Println(strings.EqualFold("Go", "go"))
2fmt.Println(strings.EqualFold("AB", "ab"))
3fmt.Println(strings.EqualFold("ß", "ss"))

Output

true
true
false

func Fields

1func Fields(s string) []string

Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space.

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

Output

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

func FieldsFunc

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

FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c) and returns an array of slices of s. If all code points in s satisfy f(c) or the string is empty, an empty slice is returned.

FieldsFunc makes no guarantees about the order in which it calls f(c) and assumes that f always returns the same value for a given c.

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

Output

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

func HasPrefix

1func HasPrefix(s, prefix string) bool

HasPrefix tests whether the string s begins with prefix.

1fmt.Println(strings.HasPrefix("Gopher", "Go"))
2fmt.Println(strings.HasPrefix("Gopher", "C"))
3fmt.Println(strings.HasPrefix("Gopher", ""))

Output

true
false
true

func HasSuffix

1func HasSuffix(s, suffix string) bool

HasSuffix tests whether the string s ends with suffix.

1fmt.Println(strings.HasSuffix("Amigo", "go"))
2fmt.Println(strings.HasSuffix("Amigo", "O"))
3fmt.Println(strings.HasSuffix("Amigo", "Ami"))
4fmt.Println(strings.HasSuffix("Amigo", ""))

Output

true
false
false
true

func Index

1func Index(s, substr string) int

Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.

1fmt.Println(strings.Index("chicken", "ken"))
2fmt.Println(strings.Index("chicken", "dmr"))

Output

4
-1

func IndexAny

1func IndexAny(s, chars string) int

IndexAny returns the index of the first instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

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

Output

2
-1

func IndexByte

1func IndexByte(s string, c byte) int

IndexByte returns the index of the first instance of c in s, or -1 if c is not present in s.

1fmt.Println(strings.IndexByte("golang", 'g'))
2fmt.Println(strings.IndexByte("gophers", 'h'))
3fmt.Println(strings.IndexByte("golang", 'x'))

Output

0
3
-1

func IndexFunc

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

IndexFunc returns the index into s of the first Unicode code point satisfying f(c), or -1 if none do.

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

Output

7
-1

func IndexRune

1func IndexRune(s string, r rune) int

IndexRune returns the index of the first instance of the Unicode code point r, or -1 if rune is not present in s. If r is utf8.RuneError, it returns the first instance of any invalid UTF-8 byte sequence.

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

Output

4
-1

func Join

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

Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string.

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

Output

foo, bar, baz

func LastIndex

1func LastIndex(s, substr string) int

LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.

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

Output

0
3
-1

func LastIndexAny

1func LastIndexAny(s, chars string) int

LastIndexAny returns the index of the last instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

1fmt.Println(strings.LastIndexAny("go gopher", "go"))
2fmt.Println(strings.LastIndexAny("go gopher", "rodent"))
3fmt.Println(strings.LastIndexAny("go gopher", "fail"))

Output

4
8
-1

func LastIndexFunc

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

LastIndexFunc returns the index into s of the last Unicode code point satisfying f(c), or -1 if none do.

1fmt.Println(strings.LastIndexFunc("go 123", unicode.IsNumber))
2fmt.Println(strings.LastIndexFunc("123 go", unicode.IsNumber))
3fmt.Println(strings.LastIndexFunc("go", unicode.IsNumber))

Output

5
2
-1

func Map

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

Map returns a copy of the string s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.

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

Output

'Gjnf oevyyvt naq gur fyvgul tbcure...

func Repeat

1func Repeat(s string, count int) string

Repeat returns a new string consisting of count copies of the string s.

It panics if count is negative or if the result of (len(s) * count) overflows.

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

Output

banana

func Replace

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

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

1fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
2fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))

Output

oinky oinky oink
moo moo moo

func Split

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

Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.

If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s.

If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.

It is equivalent to SplitN with a count of -1.

To split around the first instance of a separator, see Cut.

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

Output

["a" "b" "c"]
["" "man " "plan " "canal panama"]
[" " "x" "y" "z" " "]
[""]

func SplitAfter

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

SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings.

If s does not contain sep and sep is not empty, SplitAfter returns a slice of length 1 whose only element is s.

If sep is empty, SplitAfter splits after each UTF-8 sequence. If both s and sep are empty, SplitAfter returns an empty slice.

It is equivalent to SplitAfterN with a count of -1.

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

Output

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

func SplitAfterN

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

SplitAfterN slices s into substrings after each instance of sep and returns a slice of those substrings.

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for SplitAfter.

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

Output

["a," "b,c"]

func SplitN

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

SplitN slices s into substrings separated by sep and returns a slice of the substrings between those separators.

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for Split.

To split around the first instance of a separator, see Cut.

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

Output

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

func ToLower

1func ToLower(s string) string

ToLower returns s with all Unicode letters mapped to their lower case.

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

Output

gopher

func ToLowerSpecial

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

ToLowerSpecial returns a copy of the string s with all Unicode letters mapped to their lower case using the case mapping specified by c.

1fmt.Println(strings.ToLowerSpecial(unicode.TurkishCase, "Önnek İş"))

Output

önnek iş

func ToTitle

1func ToTitle(s string) string

ToTitle returns a copy of the string s with all Unicode letters mapped to their Unicode title case.

1fmt.Println(strings.ToTitle("her royal highness"))
2fmt.Println(strings.ToTitle("loud noises"))
3fmt.Println(strings.ToTitle("хлеб"))

Output

HER ROYAL HIGHNESS
LOUD NOISES
ХЛЕБ

func ToTitleSpecial

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

ToTitleSpecial returns a copy of the string s with all Unicode letters mapped to their Unicode title case, giving priority to the special casing rules.

1fmt.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

1func ToUpper(s string) string

ToUpper returns s with all Unicode letters mapped to their upper case.

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

Output

GOPHER

func ToUpperSpecial

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

ToUpperSpecial returns a copy of the string s with all Unicode letters mapped to their upper case using the case mapping specified by c.

1fmt.Println(strings.ToUpperSpecial(unicode.TurkishCase, "örnek iş"))

Output

ÖRNEK İŞ

func Trim

1func Trim(s, cutset string) string

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

1fmt.Print(strings.Trim("¡¡¡Hello, Gophers!!!", "!¡"))

Output

Hello, Gophers

func TrimFunc

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

TrimFunc returns a slice of the string s with all leading and trailing Unicode code points c satisfying f(c) removed.

1fmt.Print(strings.TrimFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
2	return !unicode.IsLetter(r) && !unicode.IsNumber(r)
3}))

Output

Hello, Gophers

func TrimLeft

1func TrimLeft(s, cutset string) string

TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed.

To remove a prefix, use TrimPrefix instead.

1fmt.Print(strings.TrimLeft("¡¡¡Hello, Gophers!!!", "!¡"))

Output

Hello, Gophers!!!

func TrimLeftFunc

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

TrimLeftFunc returns a slice of the string s with all leading Unicode code points c satisfying f(c) removed.

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

Output

Hello, Gophers!!!

func TrimPrefix

1func TrimPrefix(s, prefix string) string

TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

1var s = "¡¡¡Hello, Gophers!!!"
2s = strings.TrimPrefix(s, "¡¡¡Hello, ")
3s = strings.TrimPrefix(s, "¡¡¡Howdy, ")
4fmt.Print(s)

Output

Gophers!!!

func TrimRight

1func TrimRight(s, cutset string) string

TrimRight returns a slice of the string s, with all trailing Unicode code points contained in cutset removed.

To remove a suffix, use TrimSuffix instead.

1fmt.Print(strings.TrimRight("¡¡¡Hello, Gophers!!!", "!¡"))

Output

¡¡¡Hello, Gophers

func TrimRightFunc

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

TrimRightFunc returns a slice of the string s with all trailing Unicode code points c satisfying f(c) removed.

1fmt.Print(strings.TrimRightFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
2	return !unicode.IsLetter(r) && !unicode.IsNumber(r)
3}))

Output

¡¡¡Hello, Gophers

func TrimSpace

1func TrimSpace(s string) string

TrimSpace returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.

1fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))

Output

Hello, Gophers

func TrimSuffix

1func TrimSuffix(s, suffix string) string

TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

1var s = "¡¡¡Hello, Gophers!!!"
2s = strings.TrimSuffix(s, ", Gophers!!!")
3s = strings.TrimSuffix(s, ", Marmots!!!")
4fmt.Print(s)

Output

¡¡¡Hello

func NewReader

1func NewReader(s string) *Reader

NewReader returns a new Reader reading from s. It is similar to bytes.NewBufferString but more efficient and read-only.

func NewReplacer

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

NewReplacer returns a new Replacer from a list of old, new string pairs. Replacements are performed in the order they appear in the target string, without overlapping matches. The old string comparisons are done in argument order.

NewReplacer panics if given an odd number of arguments.

1r := strings.NewReplacer("<", "&lt;", ">", "&gt;")
2fmt.Println(r.Replace("This is <b>HTML</b>!"))

Output

This is <b>HTML</b>!

Types

type Builder

1type Builder struct {
2}

A Builder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use. Do not copy a non-zero Builder.

func Cap

1func (b *Builder) Cap() int

Cap returns the capacity of the builder's underlying byte slice. It is the total space allocated for the string being built and includes any bytes already written.

func Grow

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

Grow grows b's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to b without another allocation. If n is negative, Grow panics.

func Len

1func (b *Builder) Len() int

Len returns the number of accumulated bytes; b.Len() == len(b.String()).

func Reset

1func (b *Builder) Reset()

Reset resets the Builder to be empty.

func String

1func (b *Builder) String() string

String returns the accumulated string.

func Write

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

Write appends the contents of p to b's buffer. Write always returns len(p), nil.

func WriteByte

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

WriteByte appends the byte c to b's buffer. The returned error is always nil.

func WriteRune

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

WriteRune appends the UTF-8 encoding of Unicode code point r to b's buffer. It returns the length of r and a nil error.

func WriteString

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

WriteString appends the contents of s to b's buffer. It returns the length of s and a nil error.


© Matthias Hochgatterer – MastodonGithubRésumé