Method 1 – String Contains
The easiest and most popular method to check if a string contains a substring is to use the Contains() method from the strings package.
The function syntax is as:
The function takes the main string and the substring as the parameters. It returns a Boolean true if the substring is located inside the string and false if otherwise.
Consider the example below:
import"strings"
import"fmt"
funcmain() {
str := "Hello world from linuxhint"
fmt.Println(strings.Contains(str, "linuxhint"))
}
The method will check if the variable str contains the specified substring. If the substring is located inside the str, the function returns true and false if otherwise.
An example output is as shown:
true
In most cases, this is the only method you will need to check for a substring in go.
However, it does not hurt to select options for various use cases. Let us look at a few examples:
Method 2 – ContainsAny
You can also use the ContainsAny() method from the strings package. This function checks if a string contains a specified Unicode character.
For example:
import (
"fmt"
"strings"
)
funcmain() {
str := "Welcome to linuxhint 🤗"
fmt.Println(strings.ContainsAny(str, "linux"))
fmt.Println(strings.ContainsAny(str, ""))
fmt.Println(strings.ContainsAny(str, "🤗"))
}
The example above the containsAny() method to check for matching Unicode characters in a string.
An example output is as shown:
false
true
Method 3 – HasPrefix & HasSuffix
Go also provides us with two methods, HasPrefix() and HasSuffix(), to check if a substring is a prefix or a suffix of another string, respectively.
For example, to check if a substring is the prefix of a specific main string, we can do:
fmt.Println(strings.HasPrefix(str, "Welcome"))
The example above returns true, as the substring “Welcome” is the prefix of the variable str.
The same case applies for the HasSuffix() method. An example is as shown below:
fmt.Println(strings.HasSuffix(str, "Welcome"))
The example above returns false, as the string “Welcome” is not the suffix of the str variable.
Method 4 – Index
We can also use the index method to check if a string contains a specific substring. The index method takes the main string and the substring to search for as the parameters.
The function will then return the index of the first instance of the substring if it is found in the main string. If the function does not find the substring, it returns a -1 integer.
Consider the example shown below:
fmt.Println(strings.Index(str, "linuxhint"))
If we run the code above, we should get an output as:
11
The output above shows the index of the first occurrence of the match for the specified substring.
Consider the example below:
fmt.Println(strings.Index(str, "no match"))
In this example, the code above returns -1 as no match for the substring is found.
Conclusion
This guide covered various methods and techniques you can use to search if a string contains a substring.
Thank you for reading!