Go's String Manipulation
Go provides a rich set of tools for string manipulation, both in its standard library and through idiomatic patterns. Understanding these can greatly enhance your ability to work with text in Go.
Basic Operations
Concatenation
s := "Hello" + " " + "World"
String Length
len := len("Go")
Strings Package
The strings
package offers powerful functions:
Splitting
parts := strings.Split("a,b,c", ",")
Joining
joined := strings.Join([]string{"a", "b", "c"}, "-")
Contains and Index
contains := strings.Contains("seafood", "foo") index := strings.Index("chicken", "ken")
Trimming
trimmed := strings.TrimSpace(" hello ")
Efficient String Building
For complex string building, use strings.Builder
:
var b strings.Builder
for i := 0; i < 1000; i++ {
fmt.Fprintf(&b, "%d", i)
}
result := b.String()
Rune Handling
Strings in Go are UTF-8 encoded. Use runes for Unicode characters:
for _, r := range "Hello, 世界" {
fmt.Printf("%c ", r)
}
Format Strings
Use fmt.Sprintf
for complex string formatting:
s := fmt.Sprintf("Pi: %.2f", math.Pi)
Regular Expressions
For complex pattern matching, use the regexp
package:
matched, _ := regexp.MatchString(`\d+`, "123")
Mastering string manipulation in Go involves understanding these tools and knowing when to use each one. With practice, you’ll be able to handle text processing tasks efficiently and idiomatically in Go.