To check if the string is a substring of another string in Go, use the contains() method.
Golang String Contains
Golang String Contains() is a built-in function that checks whether substr is within the string. The Contains() function accepts two arguments and returns the boolean value, either true or false.
To use Contains() function in Go, import the strings package and then call the contains() method and pass the two parameters in which one is a source string and the second is the substring, which we need to check against the main string.
Syntax
func Contains(s, substr string) bool
Parameters
The first parameter is a source string, and the second parameter is the substring, which we have to check against the main string to see if it contains.
Return Value
The strings.Contains() method returns the boolean value true or false.
Implementation of String Contains() method
See the following code.
// hello.go package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Contains("MichaelJackson", "Michael")) fmt.Println(strings.Contains("MillieBobbyBrown", "Bobby")) fmt.Println(strings.Contains("AudreyGraham", "Drake")) fmt.Println(strings.Contains("Jennifer Lopez", "JLo")) }
Output
go run hello.go true true false false
With Contains, we search one string for a specified substring. Then, we see if the string is found.
In the above example, the substring appears in the main string in the first two test cases. That is why it returns true.
The source string does not contain the substring in the last two test cases. That is why it returns false.
We search for characters with other string functions like the ContainsAny() function. If any set of characters is found in the string, ContainsAny will return true.
Example 2
See the following code.
// hello.go package main import ( "fmt" "strings" ) func main() { dataA := "Javascript" dataB := "Golang" source := "this is a Golang" if strings.Contains(source, dataA) { fmt.Println("JavaScript") } if strings.Contains(source, dataB) { fmt.Println("Golang") } }
Output
go run hello.go Golang
We have a string that Contains “This language is Golang.” However, the word “Javascript” did not found in the string. So, we receive a false for the first test case.
When we invoke Contains and search for the String Golang, it returns true because the string contains the Golang substring. So it returns true and prints the line.
The strings.Contains() is more precise than Index() when we need to test existence. We can check against true and false, not the magical value -1 that Index() returns to mean “not found.”
That’s it for this tutorial.