How to Check If String Contains Substring in Golang

To check if a string contains a substring in Golang, use the strings.Contains()” function from the strings package. The strings.Contains() function returns true if the substring is present in the string or false if not.

Syntax

func Contains(s, substr string) bool

Parameters

  1. str: It is the original string and
  2. substr: It is the string that you want to check.

Example 1

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

Example 2

package main

import (
  "fmt"
  "strings"
)

// Struct to represent a Product
type Product struct {
  Name string
  Description string
}

// Function to search for products containing a keyword in their name or description
func searchProducts(products []Product, keyword string) []Product {
  var results []Product
  for _, product := range products {
    if strings.Contains(product.Name, keyword) || strings.Contains(product.Description, keyword) {
      results = append(results, product)
    }
  }
  return results
}

// Function to highlight a keyword within a text
func highlightKeyword(text, keyword string) string {
  return strings.Replace(text, keyword, "["+keyword+"]", -1)
}

func main() {
  // Sample Products
  products := []Product{
    {"Laptop", "High-performance laptop for gaming"},
    {"Mouse", "Wireless mouse with ergonomic design"},
    {"Keyboard", "Mechanical keyboard with backlight"},
    {"Monitor", "27-inch monitor with 4K resolution"},
 }

  // Searching for products containing the keyword "laptop"
  keyword := "laptop"
  searchResults := searchProducts(products, keyword)
  fmt.Println("Search Results for keyword '" + keyword + "':")
  for _, product := range searchResults {
    highlightedName := highlightKeyword(product.Name, keyword)
    highlightedDescription := highlightKeyword(product.Description, keyword)
    fmt.Println("Name:", highlightedName, "| Description:", highlightedDescription)
  }

  // Checking if a
}

Output

Search Results for keyword 'laptop':
Name: Laptop | Description: High-performance [laptop] for gaming

That’s it.

Related posts

Golang strings.Replace()