How to Use strings Package in Go: Syntax and Examples
In Go, you use the
strings package by importing it with import "strings" and then calling its functions like strings.ToUpper() or strings.Contains() to manipulate strings easily. This package provides many helpful functions for searching, replacing, splitting, and trimming strings.Syntax
To use the strings package, first import it. Then call its functions with the package name prefix. For example, strings.ToUpper(s) converts string s to uppercase.
import "strings": imports the packagestrings.FunctionName(args): calls a function from the package
go
import "strings" // Example function call upper := strings.ToUpper("hello")
Example
This example shows how to use some common functions from the strings package: converting to uppercase, checking if a substring exists, and splitting a string.
go
package main import ( "fmt" "strings" ) func main() { text := "hello, world" // Convert to uppercase upper := strings.ToUpper(text) fmt.Println("Uppercase:", upper) // Check if substring exists contains := strings.Contains(text, "world") fmt.Println("Contains 'world':", contains) // Split string by comma parts := strings.Split(text, ",") fmt.Println("Split parts:", parts) }
Output
Uppercase: HELLO, WORLD
Contains 'world': true
Split parts: [hello world]
Common Pitfalls
One common mistake is forgetting to import the strings package, which causes a compile error. Another is confusing strings.Contains() with case-insensitive search; it is case-sensitive. Use strings.Contains(strings.ToLower(s), substr) for case-insensitive checks.
go
package main import ( "fmt" "strings" ) func main() { text := "Hello, World" // Wrong: case-sensitive check fmt.Println(strings.Contains(text, "world")) // false // Right: case-insensitive check fmt.Println(strings.Contains(strings.ToLower(text), "world")) // true }
Output
false
true
Quick Reference
| Function | Description | Example |
|---|---|---|
| ToUpper(s string) string | Returns s in uppercase | strings.ToUpper("go") → "GO" |
| ToLower(s string) string | Returns s in lowercase | strings.ToLower("GO") → "go" |
| Contains(s, substr string) bool | Checks if substr is in s | strings.Contains("hello", "ll") → true |
| Split(s, sep string) []string | Splits s by sep | strings.Split("a,b,c", ",") → ["a" "b" "c"] |
| TrimSpace(s string) string | Removes spaces from start and end | strings.TrimSpace(" hi ") → "hi" |
Key Takeaways
Always import the strings package with import "strings" before using its functions.
Use strings functions like ToUpper, Contains, and Split to manipulate strings easily.
strings.Contains is case-sensitive; convert strings to lower or upper case for case-insensitive checks.
The strings package offers many useful functions for trimming, replacing, and searching strings.
Remember to handle spaces and cases properly when working with string data.