Golang Program to compare strings using library function


In this article we will write an article to compare numbers and strings using library function in Go language. we will write two programs to illustrate. In the first program we will use the external user defined function and in the second one we will use the internal library function to implement the logic.

Syntax

func Compare(s1, s2 string) int

Compare() function is used to compare the given strings in go. It is present in strings package. This function takes the strings to be compared as argument to the function and returns the integer equivalent after comparing the two strings. the integer value returned can be 0, 1 or -1. It is 0 if both the strings are equal and 1 if string 1 is greater than second string and -1 if second string is greater than the first one.

Algorithm

STEP 1 − First, we import the fmt and strings package. String package allows us to use predefined string methods.

STEP 2 − After that we have to start the main function. Now initialize two strings and store values to them.

STEP 3 − Print the strings on the screen.

STEP 4 − Call the strings.Compare() function by passing the value of strings entered by the user as arguments to it.

STEP 5 − Store the number returned by the function in seperate variables.

STEP 6 − Use conditionals to compare the value returned by the function of the two strings.

STEP 7 − Print respective results on the screen by using fmt.Println() function.

STEP 8 − Repeat the above process by taking different values to strings.

Example

In this program we will write a golang program to compare two strings using a library function count. To compare two strings we have chosen a combination of count() and if-else conditionals.

package main
import (
   "fmt"
   "strings" 
)
func main() {

   // intiaizing strings
   var string1 string
   var string2 string
   string1 = "computer"
   string2 = "apple"
   fmt.Println("The first string is:", string1)
   fmt.Println("The second string is:", string2)
   a := strings.Compare(string1, string2)
   if a == 0 {
      fmt.Print("Both strings are equal")
   } else if a < 0 {
      fmt.Print("The second string is greater than first one")
   } else {
      fmt.Println("The first string is greater than the second string")
   }
}

Output

The first string is: computer
The second string is: apple
The first string is greater than the second string

Conclusion

We have successfully compiled and executed the Go language program to compare numbers and strings using library functions along with examples. Here in this example we have used compare() function present in strings package to compare the characters of two strings. The function then returns an integer value on which we can use conditionals and print the result accordingly.

Updated on: 10-Feb-2023

548 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements