×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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

Parameters

  • 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 »




Comments and Discussions!

Load comments ↻





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