Package strings implements simple functions to manipulate UTF-8 encoded strings.
Search and Contains Functions
Contains
func Contains(s, substr string) bool
Reports whether substr is within s.fmt.Println(strings.Contains("seafood", "foo")) // true
fmt.Println(strings.Contains("seafood", "bar")) // false
ContainsAny
func ContainsAny(s, chars string) bool
Reports whether any Unicode code points in chars are within s.fmt.Println(strings.ContainsAny("team", "i")) // false
fmt.Println(strings.ContainsAny("team", "aei")) // true
ContainsRune
func ContainsRune(s string, r rune) bool
Reports whether the Unicode code point r is within s.fmt.Println(strings.ContainsRune("golang", 'g')) // true
Index
func Index(s, substr string) int
Returns the index of the first instance of substr in s, or -1 if substr is not present.fmt.Println(strings.Index("chicken", "ken")) // 4
fmt.Println(strings.Index("chicken", "duck")) // -1
LastIndex
func LastIndex(s, substr string) int
Returns the index of the last instance of substr in s, or -1 if substr is not present.fmt.Println(strings.LastIndex("go gopher", "go")) // 3
IndexByte
func IndexByte(s string, c byte) int
Returns the index of the first instance of c in s, or -1 if c is not present.
IndexRune
func IndexRune(s string, r rune) int
Returns the index of the first instance of the Unicode code point r, or -1 if rune is not present.
Count
func Count(s, substr string) int
Counts the number of non-overlapping instances of substr in s. If substr is an empty string, returns 1 + the number of Unicode code points in s.fmt.Println(strings.Count("cheese", "e")) // 3
fmt.Println(strings.Count("five", "")) // 5 (before each rune + after)
Prefix and Suffix Functions
HasPrefix
func HasPrefix(s, prefix string) bool
Tests whether the string s begins with prefix.fmt.Println(strings.HasPrefix("Gopher", "Go")) // true
fmt.Println(strings.HasPrefix("Gopher", "C")) // false
HasSuffix
func HasSuffix(s, suffix string) bool
Tests whether the string s ends with suffix.fmt.Println(strings.HasSuffix("Amigo", "go")) // true
fmt.Println(strings.HasSuffix("Amigo", "Ami")) // false
TrimPrefix
func TrimPrefix(s, prefix string) string
Returns s without the provided leading prefix string. If s doesn’t start with prefix, s is returned unchanged.fmt.Println(strings.TrimPrefix("Goodbye", "Good")) // bye
TrimSuffix
func TrimSuffix(s, suffix string) string
Returns s without the provided trailing suffix string.fmt.Println(strings.TrimSuffix("Hello!", "!")) // Hello
Splitting and Joining
Split
func Split(s, sep string) []string
Slices s into all substrings separated by sep and returns a slice of the substrings between those separators.fmt.Printf("%q\n", strings.Split("a,b,c", ",")) // ["a" "b" "c"]
fmt.Printf("%q\n", strings.Split("a man a plan", " ")) // ["a" "man" "a" "plan"]
SplitN
func SplitN(s, sep string, n int) []string
Slices s into substrings separated by sep and returns a slice with at most n substrings. The last substring will be the unsplit remainder.fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 2)) // ["a" "b,c"]
SplitAfter
func SplitAfter(s, sep string) []string
Slices s into substrings after each instance of sep.fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ",")) // ["a," "b," "c"]
Fields
func Fields(s string) []string
Splits the string s around each instance of one or more consecutive white space characters.fmt.Printf("%q\n", strings.Fields(" foo bar baz ")) // ["foo" "bar" "baz"]
Join
func Join(elems []string, sep string) string
Concatenates the elements of a slice to create a single string. The separator string sep is placed between elements.s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", ")) // foo, bar, baz
Case Conversion
ToLower
func ToLower(s string) string
Returns s with all Unicode letters mapped to their lower case.fmt.Println(strings.ToLower("Gopher")) // gopher
ToUpper
func ToUpper(s string) string
Returns s with all Unicode letters mapped to their upper case.fmt.Println(strings.ToUpper("Gopher")) // GOPHER
ToTitle
func ToTitle(s string) string
Returns s with all Unicode letters mapped to their title case.fmt.Println(strings.ToTitle("loud noises")) // LOUD NOISES
Title
func Title(s string) string
Returns a copy of the string s with all Unicode letters that begin words mapped to their title case.Note: Deprecated. Use cases.Title instead.
Trimming Functions
Trim
func Trim(s, cutset string) string
Returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.fmt.Println(strings.Trim("¡¡¡Hello, Gophers!!!", "!¡")) // Hello, Gophers
TrimSpace
func TrimSpace(s string) string
Returns a slice of the string s with all leading and trailing white space removed.fmt.Printf("%q\n", strings.TrimSpace(" \t\n a lone gopher \n\t\r\n")) // "a lone gopher"
TrimLeft
func TrimLeft(s, cutset string) string
Returns a slice of the string s with all leading Unicode code points contained in cutset removed.fmt.Println(strings.TrimLeft("!!!Hello", "!")) // Hello
TrimRight
func TrimRight(s, cutset string) string
Returns a slice of the string s with all trailing Unicode code points contained in cutset removed.fmt.Println(strings.TrimRight("Hello!!!", "!")) // Hello
Replacement Functions
Replace
func Replace(s, old, new string, n int) string
Returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If n < 0, there is no limit on the number of replacements.fmt.Println(strings.Replace("oink oink oink", "oink", "moo", 2)) // moo moo oink
fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1)) // moo moo moo
ReplaceAll
func ReplaceAll(s, old, new string) string
Returns a copy of the string s with all non-overlapping instances of old replaced by new.fmt.Println(strings.ReplaceAll("oink oink oink", "oink", "moo")) // moo moo moo
Repeat and Builder
Repeat
func Repeat(s string, count int) string
Returns a new string consisting of count copies of the string s.fmt.Println(strings.Repeat("na", 3)) // nanana
A Builder is used to efficiently build a string using Write methods. It minimizes memory copying.var b strings.Builder
b.WriteString("Hello")
b.WriteString(", ")
b.WriteString("World!")
fmt.Println(b.String()) // Hello, World!
Comparison Functions
Compare
func Compare(a, b string) int
Returns an integer comparing two strings lexicographically. Returns 0 if a == b, -1 if a < b, and +1 if a > b.fmt.Println(strings.Compare("a", "b")) // -1
fmt.Println(strings.Compare("a", "a")) // 0
fmt.Println(strings.Compare("b", "a")) // 1
EqualFold
func EqualFold(s, t string) bool
Reports whether s and t are equal under Unicode case-folding (case-insensitive comparison).fmt.Println(strings.EqualFold("Go", "go")) // true
Examples
String Manipulation
package main
import (
"fmt"
"strings"
)
func main() {
s := " Hello, World! "
// Trim whitespace
s = strings.TrimSpace(s)
fmt.Println(s) // "Hello, World!"
// Convert to lowercase
lower := strings.ToLower(s)
fmt.Println(lower) // "hello, world!"
// Replace text
s = strings.ReplaceAll(s, "World", "Gopher")
fmt.Println(s) // "Hello, Gopher!"
// Check prefix/suffix
if strings.HasPrefix(s, "Hello") {
fmt.Println("Starts with Hello")
}
}
Splitting and Joining
package main
import (
"fmt"
"strings"
)
func main() {
// Split string
csv := "apple,banana,cherry"
fruits := strings.Split(csv, ",")
fmt.Printf("%q\n", fruits) // ["apple" "banana" "cherry"]
// Join strings
joined := strings.Join(fruits, " | ")
fmt.Println(joined) // apple | banana | cherry
// Split on whitespace
text := "the quick brown fox"
words := strings.Fields(text)
fmt.Printf("%q\n", words) // ["the" "quick" "brown" "fox"]
}
Building Strings Efficiently
package main
import (
"fmt"
"strings"
)
func main() {
// Use Builder for efficient concatenation
var b strings.Builder
words := []string{"Hello", "World", "from", "Go"}
for i, word := range words {
if i > 0 {
b.WriteString(", ")
}
b.WriteString(word)
}
result := b.String()
fmt.Println(result) // Hello, World, from, Go
// Builder capacity
var b2 strings.Builder
b2.Grow(100) // Pre-allocate space
b2.WriteString("Efficient!")
}
String Searching
package main
import (
"fmt"
"strings"
)
func main() {
text := "The Go programming language"
// Check contains
if strings.Contains(text, "Go") {
fmt.Println("Found Go")
}
// Find index
index := strings.Index(text, "programming")
fmt.Printf("'programming' starts at index %d\n", index) // 7
// Count occurrences
count := strings.Count(text, "a")
fmt.Printf("Letter 'a' appears %d times\n", count) // 3
}