The strings Package
In this page:
Searching Within Strings
strings.Contains, HasPrefix, and HasSuffix check whether a string contains, starts with, or ends with a given substring, returning a simple boolean without needing manual index math.
Example: Searching Within Strings
package main
import (
"fmt"
"strings"
)
func main() {
s := "Go is fun"
fmt.Println(strings.Contains(s, "fun"))
fmt.Println(strings.HasPrefix(s, "Go"))
fmt.Println(strings.HasSuffix(s, "fun"))
}
Login to try C/C++/Java/PHP code in the editor
Splitting and Joining
strings.Split breaks a string into a slice of substrings around a separator, while strings.Join does the opposite, combining a slice of strings into one, joined by a given separator.
Example: Splitting and Joining
package main
import (
"fmt"
"strings"
)
func main() {
parts := strings.Split("apple,banana,cherry", ",")
fmt.Println(parts)
joined := strings.Join(parts, " | ")
fmt.Println(joined)
}
Login to try C/C++/Java/PHP code in the editor
Case Conversion and Trimming
strings.ToUpper and ToLower normalize case, while strings.TrimSpace removes leading and trailing whitespace -- all common steps before comparing or displaying user-provided text.
Example: Case Conversion and Trimming
package main
import (
"fmt"
"strings"
)
func main() {
raw := " Hello Go "
fmt.Println(strings.ToUpper(strings.TrimSpace(raw)))
}
Login to try C/C++/Java/PHP code in the editor
Replacing Substrings
strings.ReplaceAll swaps every occurrence of a substring for another, while strings.Replace lets you limit how many occurrences are replaced with an explicit count argument.
Example: Replacing Substrings
package main
import (
"fmt"
"strings"
)
func main() {
s := "one two two three"
fmt.Println(strings.ReplaceAll(s, "two", "2"))
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting strings.Split on a separator not found in the string still returns a one-element slice containing the whole original string.
- Using strings.Replace with the wrong count argument (n), not realizing 0 replaces nothing and -1 replaces all occurrences.
- Assuming strings.Contains is case-insensitive -- it's a strict substring match; use strings.EqualFold or lowercase both sides for case-insensitive comparisons.
- strings.Contains, strings.HasPrefix, and strings.HasSuffix check for substrings at various positions.
- strings.Split breaks a string into a slice using a separator; strings.Join does the reverse.
- strings.ToUpper/ToLower/TrimSpace normalize text for comparison or display.
- strings.Replace and strings.ReplaceAll substitute occurrences of a substring.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: