×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to demonstrate the strings.Compare() function

Here, we are going to demonstrate the strings.Compare() function in Golang (Go Language).
Submitted by Nidhi, on March 17, 2021 [Last updated : March 03, 2023]

strings.Compare() function in Golang

Problem Solution:

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

Program/Source Code:

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

Golang code to demonstrate the example of strings.Compare() function

// 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 str1, str2, which are initialized with "abc", "xyz" respectively. After that, we compare both strings using relational operators (<, >, ==) and print the result on the console screen.

Golang String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.