strings.Contains() method in Golang

Contains() method is a part of the strings package in the Go language. This post will look at the Contains() method in detail.

  • Method declaration – func Contains(s, substr string) bool 
  • What does it do? It checks whether or not the substr passed in the arguments ( 2nd argument ) is present within the s ( 1st argument ).
  • What does it return? It will return true if substr is present in the given string. Otherwise, it will return false.

So, the Contains() method will help you find whether a string contains another string. Let’s see this in action with an example.

package main

import (
	"fmt"
	"strings"
)

func main() {

	str := "codekru"

	var result1 bool = strings.Contains(str, "code")
	var result2 bool = strings.Contains(str, "hello")

	fmt.Println("Is \"code\" present in \"codekru\"? ", result1)
	fmt.Println("Is \"hello\" present in \"codekru\"? ", result2)

}

Output –

Is "code" present in "codekru"?  true
Is "hello" present in "codekru"?  false

Contains() method internally uses the Index() method, and if the Index() method returns a value greater than or equal to 0, then the Contains() method returns true, otherwise false.

Internal Implementation of the Contains() method
func Contains(s, substr string) bool {
	return Index(s, substr) >= 0
}

The What If scenarios

Q – What if we try to check whether a string contains an empty string or not?

It will return true as illustrated by the below example

package main

import (
	"fmt"
	"strings"
)

func main() {

	str := "codekru"

	var isEmptyStringPresent bool = strings.Contains(str, "")
	fmt.Println("is empty string present?", isEmptyStringPresent)

}

Output –

is empty string present? true
Q – What if we don’t initialize a string and try to find an empty string using the Contains() method?
package main

import (
	"fmt"
	"strings"
)

func main() {

	var str string

	var isEmptyStringPresent bool = strings.Contains(str, "")
	fmt.Println(isEmptyStringPresent)

}

Output –

true

So, what happened here?

  • Here, we have only declared a string and have not initialized it to any value. So, by default, it will assume its zero value which is an empty string.
  • So, the strings.Contains(str, “”) effectively looks like strings.Contains(“”,””)
  • And, Contains() method returned true as both strings are the same ( even though they are empty).

Please visit this link to learn more about the Strings in Go language and its other functions or methods.

We hope you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Related Article
Liked the article? Share this on

3 thoughts on “strings.Contains() method in Golang”

Leave a Comment

Your email address will not be published. Required fields are marked *