One popular operation is to check if a string contains a substring. Go allows you to check if a specific set of characters is available in a string using the contains method.
This article will discuss how to use the contains method and look at a few examples of searching for a substring.
Strings.Contains()
The Go contains method is part of the strings package. Hence, you must import the “strings” package before using it.
The function takes a string and a substring as the parameters. It then checks if the string contains the specified substring. It returns a Boolean true if the substring is found and false if otherwise.
The syntax of the contains() method is as shown:
The “str” is the main string in which to search, and the “substr” refers to the substring to search for.
Practical Examples
Let us look at a few examples of using the contains() method.
Example 1
Consider the example below:
import (
"fmt"
"strings"
)
func main() {
str := "LinuxHint - Home of the best tech articles."
substr := "tech"
fmt.Println(strings.Contains(str, substr))
fmt.Println(strings.Contains(str, "articles"))
fmt.Println(strings.Contains(str, "😊"))
fmt.Println(strings.Contains(str, "not there"))
}
In the above example, we check if the substring “tech” is contained in the str. In the first example, we use a variable name.
In the second example, we pass a string literal. This shows that you can pass either a string variable or a string literal.
In the third example, we check for a Unicode character as shown by the emoji. Since the character is not in the string, the function returns false, as shown in the output below:
true
true
false
false
Example 2
You can use conditional logic to perform an action if the substring is found in the string. Consider the example below:
import (
"fmt"
"strings"
)
func main() {
str := "LinuxHint - Home of the best tech articles."
substr := "tech"
if strings.Contains(str, substr) {
fmt.Printf("substring found!")
} else {
fmt.Println("substring not found!")
}
}
The example uses the string.contains() method as the condition. This is because the function returns a Boolean value.
If the function finds the substring, the code inside the if block is executed; otherwise, the code inside the else block is run.
The resulting output is as:
substring found!
Conclusion
Using this guide, you discovered how to search if a string contains a specific substring. The contains() method is very useful and makes your work easier. Consider using it.
Happy Coding!