Strings
Strings in Go are immutable sequences of bytes, typically used to represent UTF-8 encoded text. Go provides rich support for string manipulation through the strings package and built-in operations.
Key Points
- Strings are immutable - once created, they cannot be changed
- Strings are represented as UTF-8 encoded byte sequences
- Use double quotes for string literals:
"hello" - Use backticks for raw string literals:
`hello\nworld` - String concatenation creates new strings
- Indexing a string returns bytes, not characters
- The
stringspackage provides extensive string manipulation functions - Use
len()to get byte length, not character count
String Basics
Strings can be created using double quotes or backticks for raw strings:
package main
import "fmt"
func main() {
// Regular string with double quotes
s1 := "Hello, World!"
fmt.Println(s1)
// Raw string with backticks (ignores escape sequences)
s2 := `Line 1
Line 2
Line 3`
fmt.Println(s2)
// String concatenation
greeting := "Hello" + " " + "World"
fmt.Println(greeting)
// String length (in bytes)
fmt.Println("Length:", len(s1))
// Accessing bytes
fmt.Println("First byte:", s1[0])
}Hello, World!
Line 1
Line 2
Line 3
Hello World
Length: 13
First byte: 72String Operations
The strings package provides many useful functions for working with strings:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello, Go Programming"
// Check if string contains substring
fmt.Println("Contains 'Go':", strings.Contains(s, "Go"))
// Count occurrences
fmt.Println("Count 'o':", strings.Count(s, "o"))
// Check prefix/suffix
fmt.Println("Starts with 'Hello':", strings.HasPrefix(s, "Hello"))
fmt.Println("Ends with 'ing':", strings.HasSuffix(s, "ing"))
// Find index
fmt.Println("Index of 'Go':", strings.Index(s, "Go"))
// Join strings
parts := []string{"Go", "is", "awesome"}
joined := strings.Join(parts, " ")
fmt.Println("Joined:", joined)
// Split strings
split := strings.Split(s, " ")
fmt.Println("Split:", split)
// Replace
replaced := strings.Replace(s, "Go", "Golang", 1)
fmt.Println("Replaced:", replaced)
// Case conversion
fmt.Println("Upper:", strings.ToUpper(s))
fmt.Println("Lower:", strings.ToLower(s))
// Trim whitespace
padded := " spaces "
fmt.Println("Trimmed:", strings.TrimSpace(padded))
}Contains 'Go': true
Count 'o': 3
Starts with 'Hello': true
Ends with 'ing': true
Index of 'Go': 7
Joined: Go is awesome
Split: [Hello, Go Programming]
Replaced: Hello, Golang Programming
Upper: HELLO, GO PROGRAMMING
Lower: hello, go programming
Trimmed: spacesCommon String Functions
| Function | Description | Example |
|---|---|---|
strings.Contains(s, substr) | Check if string contains substring | strings.Contains("hello", "lo") |
strings.Count(s, substr) | Count non-overlapping instances | strings.Count("cheese", "e") |
strings.HasPrefix(s, prefix) | Check if string starts with prefix | strings.HasPrefix("go", "g") |
strings.HasSuffix(s, suffix) | Check if string ends with suffix | strings.HasSuffix("go", "o") |
strings.Index(s, substr) | Find index of first occurrence | strings.Index("hello", "l") |
strings.Join(slice, sep) | Join slice elements with separator | strings.Join([]string{"a","b"}, "-") |
strings.Split(s, sep) | Split string by separator | strings.Split("a-b-c", "-") |
strings.Replace(s, old, new, n) | Replace first n occurrences | strings.Replace(s, "a", "b", 1) |
strings.ToLower(s) | Convert to lowercase | strings.ToLower("HELLO") |
strings.ToUpper(s) | Convert to uppercase | strings.ToUpper("hello") |
strings.TrimSpace(s) | Remove leading/trailing whitespace | strings.TrimSpace(" hi ") |
String Building
| Method | Performance | Use Case |
|---|---|---|
+ operator | Slow for many concatenations | Concatenating few strings |
strings.Builder | Fast, minimal allocations | Building strings in loops |
fmt.Sprintf | Moderate | Formatted string construction |
strings.Join | Fast for slices | Joining slice of strings |
String Characteristics
| Feature | Description | Notes |
|---|---|---|
| Immutability | Strings cannot be modified | Modifications create new strings |
| UTF-8 Encoding | Strings are UTF-8 by default | Supports international characters |
| Byte Sequences | Strings are byte arrays | Indexing returns bytes, not runes |
| Length | len() returns byte count | Not the same as character count |
| Comparison | Compared lexicographically | Use ==, <, > |
| Zero Value | Empty string "" | Not nil |