Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Check if a string contains another string in Go (Golang)

Posted on March 10, 2023March 10, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

In Golang string are UTF-8 encoded. strings package of GO provides a Contains method that can be used to check if a particular string is a substring of another string.

Below is the signature of the function

func Contains(s, substr string) bool

As you can notice the return value of the Compare function is an bool . This value will be

  • true is substr is present in s
  • false is substr is not present in s

Code:

package main
import (
"fmt"
"strings"
)
func main() {
present := strings.Contains("abc", "ab")
fmt.Println(present)
present = strings.Contains("abc", "xyz")
fmt.Println(present)
}

Output:

true
false

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2023 Welcome To Golang By Example | Design: Web XP