AppDividend
Latest Code Tutorials

Golang String Contains: How to Use Contains() Function In Go

0

To use Contains() function, import the strings package and then call the contains() method and pass the two parameters. First, the first parameter is a source string, and the second parameter is the substring, which we need to check against the main string.

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 check if the string is a substring of another string in Go, use the contains() method.

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. 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 the 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 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.”

See also

How to compare strings in Go

Golang String to Rune

Golang String to float

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.