How to Check if String Contains Substring in Go
In Go, you can check if a string contains a substring using the
strings.Contains function. It returns true if the substring is found and false otherwise.Syntax
The strings.Contains function takes two string arguments: the main string and the substring to search for. It returns a boolean value indicating if the substring exists inside the main string.
- strings.Contains(s, substr string) bool
s: The string to search within.substr: The substring to find.- Returns
trueifsubstris found ins, otherwisefalse.
go
package main import ( "fmt" "strings" ) func main() { result := strings.Contains("hello world", "world") fmt.Println(result) // true }
Output
true
Example
This example shows how to check if a substring exists in a string and prints a message based on the result.
go
package main import ( "fmt" "strings" ) func main() { text := "Go is fun" substr := "fun" if strings.Contains(text, substr) { fmt.Printf("The text '%s' contains '%s'.\n", text, substr) } else { fmt.Printf("The text '%s' does not contain '%s'.\n", text, substr) } }
Output
The text 'Go is fun' contains 'fun'.
Common Pitfalls
One common mistake is to check substring presence by comparing the result of strings.Index incorrectly or by using equality operators. Also, strings.Contains is case-sensitive, so "Fun" and "fun" are different.
Wrong approach example:
if strings.Index(text, substr) == -1 {
fmt.Println("Substring not found")
}Right approach:
if strings.Contains(text, substr) {
fmt.Println("Substring found")
}To ignore case, convert both strings to lower or upper case before checking.
go
package main import ( "fmt" "strings" ) func main() { text := "Hello World" substr := "world" // Case-sensitive check (will be false) fmt.Println(strings.Contains(text, substr)) // Case-insensitive check fmt.Println(strings.Contains(strings.ToLower(text), strings.ToLower(substr))) }
Output
false
true
Quick Reference
strings.Contains(s, substr): returns true ifsubstris ins.- Case-sensitive check.
- Use
strings.ToLowerorstrings.ToUpperfor case-insensitive checks. - Returns a boolean value.
Key Takeaways
Use strings.Contains to check if a substring exists in a string in Go.
strings.Contains returns a boolean: true if found, false if not.
The check is case-sensitive; convert strings to lower or upper case for case-insensitive checks.
Avoid using equality or index comparisons incorrectly; strings.Contains is simpler and clearer.
Import the strings package to use strings.Contains.