How to compare strings in golang?

by raul_reichert , in category: Golang , 2 years ago

How to compare strings in golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@raul_reichert You can use either strings.Compare() or == to compare any strings in Golang, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
   "fmt"
   "strings"
)

func main() {

   str1 := "test"
   str2 := "test"

   // Output: Strings are equal
   if strings.Compare(str1, str2) == 0 {
      fmt.Println("Strings are equal")
   }

   // Or use == to compare strings
   // Output: Strings are equal
   if str1 == str2 {
      fmt.Println("Strings are equal")
   }
} 

Member

by cyril , a year ago

@raul_reichert 

In Golang, you can compare strings using the == operator. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import "fmt"

func main() {
    str1 := "hello"
    str2 := "world"
    str3 := "hello"

    if str1 == str2 {
        fmt.Println("str1 and str2 are equal")
    } else {
        fmt.Println("str1 and str2 are not equal")
    }

    if str1 == str3 {
        fmt.Println("str1 and str3 are equal")
    } else {
        fmt.Println("str1 and str3 are not equal")
    }
}


In this example, the == operator is used to compare str1 and str2, and then str1 and str3. The output of the program is:

1
2
str1 and str2 are not equal
str1 and str3 are equal


Note that in Golang, string comparison is case-sensitive. So, for example, "hello" and "Hello" are considered different strings. If you need to compare strings ignoring case, you can use the strings.ToLower() function to convert both strings to lowercase before comparing them.