A string is a ubiquitous data structure, typically a built-in data type in programming languages. However, beneath the surface, strings are essentially arrays of characters that enable textual data storage and manipulation.
In Go, strings are a data type. Behind the scenes strings are a slice of bytes. The strings
package provides several useful convenience functions. Examples include:
- Index, Contains, HasPrefix, HasSuffix
- Split, Fields, Join
- Repeat
- ReplaceAll
- Title, ToLower, ToUpper
- Trim, TrimSpace, TrimSuffix, TrimPrefix
When a string is iterated in Go using the range
keyword, every element becomes a rune which is an alias for the type int32
. If the code being written works with many single-character strings, it is better to define variables and function parameters as rune
. The following code shows how to iterate through a string.
package main
import (
"fmt"
)
func main() {
for i, r := range "abcd" {
fmt.Printf("Char #%d %q has value %d\n", i, string(r), r)
}
}
Strings have the same complexity as arrays and slices in Go.
Unlike many other programming languages, regular expressions are guaranteed to have O(n) time complexity in Go, allowing efficient string pattern matching.
Strings store words, characters, sentences, etc.