Home » Golang String Contains

Golang String Contains

Golang strings package Contains() is a built-in function is used to check if a string contains the substring in go. It returns true if a substring is within the string else returns false.

Contains() Syntax

The syntax for Contains() function is:

func Contains(s1, substr string) bool

Contains() Parameters:

The Contains() function take two parameters

s1- string
substr- string

Contains() Return Value

The strigs package Contains() function returns bool value.

  • Returns true – if the s1 string contains the substr
  • Returns false – if s1 string doesn’t cotnains substr

Let’s understand the string package Contains() method with examples.

strings.Contains() function to check string contains substring in go

The following go program checks if a string contains the specified substring using the strings.Contains() function.

package main

import (
	"fmt"
	"strings"
)

func main() {
	var s1 = "I love Go Programming!"
	var str1 = "Go"
	var str2 = "program"
        var str3 = "Program"

	// Check s1 contains substr in go
	fmt.Println(strings.Contains(s1, str1))
	fmt.Println(strings.Contains(s1, str2))
        fmt.Println(strings.Contains(s1, str3))
}

The output of the above string contains another string in go is:

true
false
true

In the above program, the first output returns true as the s1 string contains a substring “Go”.

The second output returns false as the specified substring “program” in the s1 string. Golang is case-sensitive. Hence “program” and “Program” are different.

The third output returns true as the Contains function check if the s1 string contains the “Program” substring and returns true.

Cool Tip: How to use the string Compare function in Golang!

Conclusion

I hope the above article on how to check if the string contains a substring in golang using the Contains() method is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment