×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strings.Contains() Function with Examples

Golang | strings.Contains() Function: Here, we are going to learn about the Contains() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 15, 2021

strings.Contains()

The Contains() function is an inbuilt function of strings package which is used to check whether the string contains the given substring, it accepts two parameters – the first parameter is the string in which we have to check the substring and the second parameter is the substring to be checked. It returns a Boolean value. The result will be true if the string contains the substring, false otherwise.

Syntax

func Contains(str, substr string) bool

Parameters

  • str : String in which we have to check the substring.
  • substr : Substring to be checked.

Return Value

The return type of Contains() function is a bool, it returns true if str contains the substr, false otherwise.

Example 1

// Golang program to demonstrate the
// example of strings.Contains() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Contains("Hello, world!", "Hello"))
	fmt.Println(strings.Contains("Hello, world!", "world"))
	fmt.Println(strings.Contains("Hello, world!", "Hi"))
}

Output:

true
true
false

Example 2

// Golang program to demonstrate the
// example of strings.Contains() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str1 string = "New Delhi, India"
	var str2 string = "Los Angeles, California"
	var substr string

	substr = "Delhi"
	if strings.Contains(str1, substr) == true {
		fmt.Printf("\"%s\" contains \"%s\"\n", str1, substr)
	} else {
		fmt.Printf("\"%s\" does not contain \"%s\"\n", str1, substr)
	}

	if strings.Contains(str2, substr) == true {
		fmt.Printf("\"%s\" contains \"%s\"\n", str2, substr)
	} else {
		fmt.Printf("\"%s\" does not contain \"%s\"\n", str2, substr)
	}

	substr = "California"
	if strings.Contains(str1, substr) == true {
		fmt.Printf("\"%s\" contains \"%s\"\n", str1, substr)
	} else {
		fmt.Printf("\"%s\" does not contain \"%s\"\n", str1, substr)
	}

	if strings.Contains(str2, substr) == true {
		fmt.Printf("\"%s\" contains \"%s\"\n", str2, substr)
	} else {
		fmt.Printf("\"%s\" does not contain \"%s\"\n", str2, substr)
	}
}

Output:

"New Delhi, India" contains "Delhi"
"Los Angeles, California" does not contain "Delhi"
"New Delhi, India" does not contain "California"
"Los Angeles, California" contains "California"

Golang strings Package Functions »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.