How to check if a string contains a substring in Golang?


We know that substrings are a contiguous sequence of characters in a string, and in order to check whether a string contains a substring, we have two options available.

The first approach is to use a built-in function called Contains() and the second approach is to make use a self-written logic for the same.

The syntax for the Contains() function of the strings package is shown below.

func Contains(s, substr string) bool

In the above syntax, there are two parameters inside the function Contains(). The first parameter is the string in which we are trying to find the pattern, and the second is the pattern that we are trying to find.

Let's consider the first approach first.

Example 1

Consider the code shown below.

package main
import (
   "fmt"
   "strings"
)
func main() {
   var name string = "TutorialsPoint"
   fmt.Println(strings.Contains(name, "Point"))
}

Output

If we run the above code with the command go run main.go, then we will get the following output in the terminal.

true

Now that we have seen the most used approach when it comes to finding a substring in the above string, let's consider a code that works the same, but the logic is self-written.

Example 2

Consider the code shown below.

package main
import (
   "fmt"
)
func main() {
   var name string = "TutorialsPoint"
   var wordToSearch string = "Point"
   res := checkIfExists(name, wordToSearch)
   if res {
      fmt.Println(wordToSearch, "is present inside the string", name)
   } else {
      fmt.Println(wordToSearch, "is not present inside the string", name)
   }
}
func checkIfExists(name, word string) bool {
   l := len(name) - len(word)
   for i := 0; i <= l; i++ {
      if patternMatch(name, i, word) {
         return true
      }
   }
   return false
}
func patternMatch(name string, index int, word string) bool {
   i := index
   for j := 0; j < len(word); j++ {
      if name[i] != word[j] {
         return false
      }
      i++
   }
   return true
}

In the above code, the function checkIfExists() is used to find the pattern in a string, which in turn calls the patternMatch function.

Output

If we run the above code with the command go run main.go, then we will get the following output in the terminal.

Point is present inside the string TutorialsPoint

Updated on: 21-Feb-2022

661 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements