How to use Contains() function in Golang?

Go ProgrammingServer Side ProgrammingProgramming

Golang has a set of built-in string functions that we can utilize to perform different types of operations on string data. Contains() is such a function that can be used to search whether a particular text/string/character is present in a given string. If the text/string/character is present in the given string, then it returns True; else it returns False.

Syntax

func Contains(s, substr string) bool

Where, s is the original string and substr is the string which is to be checked with the original string.

Example

The following example demonstrates how Contains() works −

package main
// importing fmt and strings
import (
   "fmt"
   "strings"
)
// using the strings.Contains() function
func main() {
   fmt.Println(strings.Contains("AndhraPradesh", "Pradesh"))
   fmt.Println(strings.Contains("MadhyaPradesh", "Madhya"))
   fmt.Println(strings.Contains("CapitalCity", "Delhi"))
   fmt.Println(strings.Contains("UttarPradesh", "Uttar"))
}

Output

It will produce the following output −

true
true
false
true

Notice that the original string "CapitalCity" in the third statement does not contain the substring "Delhi", hence it returns False. For the remaining three comparisons, it returns True.

Example

Let us take another example −

package main
// importing fmt and strings
import (
   "fmt"
   "strings"
)
// Using the strings.Contains function
func main() {
   A := "ContainsFunction"
   C := "Function"
   if strings.Contains(A, C) {
      fmt.Println("The String contains the Substring.")
   } else {
      fmt.Println("The String does not contain the Substring.")
   }
}

Output

On execution, it will produce the following output −

The String contains the Substring.
raja
Updated on 10-Mar-2022 06:42:28

Advertisements