Golang String Contains Function | Contains() Function In Go
Golang String Contains() is an inbuilt function that checks whether substr is within the string. If you want to check if the string is a substring of another string in Go, then use Go contains() method. First, import the strings package and then call the contains() method and pass the two parameters. The first parameter is a source string, and the second parameter 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 or not.
Return Value
The strings.Contains() method returns the boolean value true or false.
Golang String Contains Example
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. We see if the string is found.
In the above example, in the first two test cases, the substring appears in the main string. That is why it returns true.
In the last two test cases, the source string does not contain the substring. That is why it returns false.
With other string functions like ContainsAny() function, we search for characters. If any of a 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.” The word “Javascript” did not found in the string. So, we receive 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 just need to test existence. We can check against true and false, not the magical value -1 that Index() returns to mean “not found.”