How do I Compare Strings in Golang?

Published April 02, 2021

In this example we will cover compare two string in golang. To compare strings we will use the golang compare() function. The string compare() function will take two string arguments as input

syntax

func Compare(a, b string) int

 

This function compare two string lexicographically and returns an integer value as 0, 1 and -1

return 0: if both strings are equal

return 1: if the string a > String b

return -1: if the string a < String b

 

Example 1 : golang compare two strings

package main

import (
"fmt"
"strings"
)

func main() {
    fmt.Println(strings.Compare("String compare", "String compare"))
    fmt.Println(strings.Compare("A", "a"))
    fmt.Println(strings.Compare("BB", "BB"))
}

 

output

0
-1
0

 

Example 2: Compare String with Custom function


package main

import "fmt"

func main() {
    s1 := "String compare golang"
    s2 := "String compare golang;"
    s3 := "ABCDEFGHI"
    s4 := "ABCDEFGHI"
    fmt.Println(customCompare(s1, s2))
    fmt.Println(customCompare(s1, s3))
    fmt.Println(customCompare(s2, s3))
    fmt.Println(customCompare(s3, s4))
}

type StrCount map[string]int

func customCompare(s1 string, s2 string) bool {
    if len(s1) != len(s2) {
        return false
    }

    m1 := make(StrCount)
    m2 := make(StrCount)
    for i := 0; i < len(s1); i++ {
        m1[string(s1[i])]++
        m2[string(s2[i])]++
    }

    return compareMap(m1, m2)
}

func compareMap(m1 StrCount, m2 StrCount) bool {
    if len(m1) != len(m2) {
        return false
    }

    for k, _ := range m1 {
        if m1[k] != m2[k] {
            return false
        }
    }

    return true
}

 

 

Execute at golang playgroung

Output

false
false
false
true

 

Related:

How to split string in golang example

 

Tags: Golang tutorial, Compare two strings,

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

781 Views