Go String Functions
Go's standard library provides a powerful strings package for working with text. Here are the most common functions you'll use.
Basic Examples
| package main
import (
"fmt"
"strings"
)
func main() {
s := "test"
// 1. Searching
fmt.Println("Contains: ", strings.Contains(s, "es")) // true
fmt.Println("Count: ", strings.Count(s, "t")) // 2
fmt.Println("HasPrefix: ", strings.HasPrefix(s, "te")) // true
fmt.Println("HasSuffix: ", strings.HasSuffix(s, "st")) // true
fmt.Println("Index: ", strings.Index(s, "e")) // 1
// 2. Joining and Splitting
fmt.Println("Join: ", strings.Join([]string{"a", "b"}, "-")) // a-b
fmt.Println("Split: ", strings.Split("a-b-c-d-e", "-")) // [a b c d e]
// 3. Transformation
fmt.Println("Repeat: ", strings.Repeat("a", 5)) // aaaaa
fmt.Println("Replace: ", strings.Replace("foo", "o", "0", -1)) // f00
fmt.Println("Replace: ", strings.Replace("foo", "o", "0", 1)) // f0o
fmt.Println("ToLower: ", strings.ToLower("TEST")) // test
fmt.Println("ToUpper: ", strings.ToUpper("test")) // TEST
}
|
Reference Table
| Function |
What it does |
Contains(s, substr) |
Returns true if substr is in s. |
Count(s, substr) |
Returns how many times substr appears. |
HasPrefix(s, prefix) |
Checks if s starts with prefix. |
Index(s, substr) |
Returns the position of the first substr. |
Join(slice, sep) |
Combines a slice of strings into one. |
Split(s, sep) |
Breaks a string into a slice. |
ToLower / ToUpper |
Changes the case. |
Note on Efficiency
If you're building a long string piece by piece (like in a loop), don't use +. Instead, use strings.Builder. It's much faster because it doesn't create a new string every time you add to it.
| var b strings.Builder
for i := 0; i < 10; i++ {
b.WriteString("word")
}
fmt.Println(b.String())
|