Trending Articles       10 Flutter Listview Examples       Flutter Custom Button Example       Flutter Audio Recording       Flutter 2.0 Autocomplete TextField       Current Location Google Maps

Golang String.Contains - How to check String contains sub string

In this golang tutorial we will cover how to check a string contains a sub string.The String package in go language provides a method called Contains() is used to check the given string is contains are not. This String.Contains() takes two parameters, first parameter is a String and second is sub string which is need to check

package main

import (
    "fmt"
    "strings"
)


// https://play.golang.org/p/lmGJcyb5RP6
func main() {
	str := "Sting Contains sub string"
	fmt.Println(strings.Contains(str, "sub")) 
	fmt.Println(strings.Contains(str, "golang")) 
    fmt.Println(strings.Contains("", ""))
}

 

 

Output:

true

false

true

 

Using string.ContainsAny()

The ContainsAny() method will check any Unicode character in the second argument is exist in the first argument

Example

package main

import (
"fmt"
"strings"
)

func main() {
    fmt.Println(strings.ContainsAny("Sachin", "a"))
    fmt.Println(strings.ContainsAny("Kohli", "z"))
    fmt.Println(strings.ContainsAny("Rohit", "r"))
    fmt.Println(strings.ContainsAny("Dhoni", "ni"))
    fmt.Println(strings.ContainsAny("", ""))
}

 

Output

true
false
false
true
false

 

Using strings.HasPrefix

HasPrefix method return true if the second argument string is a prefix of the first argument

 

Example

package main

import (
"fmt"
"strings"
)

func main() {
    fmt.Println(strings.HasPrefix("Cipher", "Ci"))
    fmt.Println(strings.HasPrefix("Golang", "go"))
    fmt.Println(strings.HasPrefix("SubString contains", "Sub"))
}

 

Output

true
false
true

 

Using strings.HasSuffix

Similar to HasPrefix, HasSuffix will returns true if the string ends with second argument

package main

import (
"fmt"
"strings"
)

func main() {
    fmt.Println(strings.HasSuffix("Mango", "go"))
    fmt.Println(strings.HasSuffix("For Loops", "Op"))
    fmt.Println(strings.HasSuffix("Man ki bath", "ki"))
}

 

Output

true
false
false

 

 

Using regex to check the sub string of the string in golang

Example

package main

import (
"fmt"
"regexp"
)

func main() {
    str := "The Crazy dogs always think like inteligent"
    matched, err := regexp.MatchString("li.*", str)
    if err != nil {

    }

    fmt.Println(matched) // true
}

 

Read More golang regex examples

 

Execute at golang playgroung

Tags: Golang tutorial, Compare two strings,


28 Views

Author: RRTutors