strings

package standard library
go1.27.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 1, 2026 License: BSD-3-Clause Imports: 11 Imported by: 2,683,284

Documentation

Overview

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

For information about UTF-8 strings in Go, see https://blog.golang.org/strings.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Clone added in go1.18

func Clone(s string) string

Clone returns a fresh copy of s. It guarantees to make a copy of s into a new allocation, which can be important when retaining only a small substring of a much larger string. Using Clone can help such programs use less memory. Of course, since using Clone makes a copy, overuse of Clone can make programs use more memory. Clone should typically be used only rarely, and only when profiling indicates that it is needed. For strings of length zero the string "" will be returned and no allocation is made.

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 added in go1.5

func Compare(a, b string) int

Compare returns an integer comparing two strings lexicographically. The result will be 0 if a == b, -1 if a < b, and +1 if a > b.

Use Compare when you need to perform a three-way comparison (with slices.SortFunc, for example). It is usually clearer and always faster to use the built-in string comparison operators ==, <, >, and so on.

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 reports whether substr is within 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 reports whether any Unicode code points in chars are within s.