Q:

Golang program to demonstrate the strings.Compare() function

belongs to collection: Golang String Programs

0

In this program, we will create two strings and compare them using strings.Compare() function. The strings.Compare() function returns a integer value.

If we have two strings str1 and str2 then,

  • If str1==str2 then it return 0
  • If str1<str2 then it return -1
  • If str1>str2 then it return 1

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the strings.Compare() function is given below. The given program is compiled and executed successfully.

// Golang program to demonstrate the
// strings.Compare() function.

package main

import "fmt"
import "strings"

func main() {
	str1 := "abc"
	str2 := "xyz"

	fmt.Println(strings.Compare(str1, str2))
	fmt.Println(strings.Compare(str2, str1))
	fmt.Println(strings.Compare(str1, str1))
}

Output:

-1
1
0

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created two string variables str1str2, which are initialized with "abc", "xyz" respectively. After that, we compare both strings using relational operators (<, >, ==) and print the result on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to demonstrate the strings.Contains... >>
<< Golang program to trim specified characters from t...