ADVERTISEMENT
ADVERTISEMENT

Golang strings.Compare() Function with Examples

Golang | strings.Compare() Function: Here, we are going to learn about the Compare() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 15, 2021

strings.Compare()

The Compare() function is an inbuilt function of strings package which is used to compare two strings, it accepts two parameters and returns an integer value comparing the strings lexicographically. The result will be 0 if both strings are the same, -1 if the first string is less than the second string, and +1 if the first string is greater than the second string.

Syntax:

func Compare(str1, str2 string) int

Parameter(s):

  • str1 : First string to be compared.
  • str2 : Second string to be compared.

Return Value:

The return type of Compare() function is an int, it returns 0 if both strings are the same, -1 if the first string is less than the second string, and +1 if the first string is greater than the second string.

Example 1:

// Golang program to demonstrate the
// example of strings.Compare() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Compare("abc", "abc"))
	fmt.Println(strings.Compare("abc", "abd"))
	fmt.Println(strings.Compare("xyz", "pqr"))
}

Output:

0
-1
1

Example 2:

// Golang program to demonstrate the
// example of strings.Compare() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str1 string = "Alex"
	var str2 string = "Boby"
	var str3 string = "Catherine"

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

Output:

-1
-1
1

Golang strings Package Functions »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.