How to Check If String Contains Substring in Golang

To check if a string contains a substring in Golang, you can use the strings.Contains() function from the strings package.

Example

package main

import (
  "fmt"
  "strings"
)

func main() {
  str := "Hello, Go is awesome!"
  substr := "Go"

  if strings.Contains(str, substr) {
    fmt.Printf("String '%s' contains the substring '%s'.\n", str, substr)
  } else {
    fmt.Printf("String '%s' does not contain the substring '%s'.\n", str, substr)
  }
}

Output

String 'Hello, Go is awesome!' contains the substring 'Go'.

In this example, we used a strings.Contains() function to check if the str contains the substr.

The function returns true if the substring is found and false otherwise. We then printed a message based on the result.

Remember to import the strings package to use the strings.Contains() function.

That’s it.

Leave a Comment