Golang 使用库函数比较字符串

Golang 使用库函数比较字符串

在这篇文章中,我们将写一篇文章来比较数字和字符串在Go语言中使用库函数。我们将编写两个程序来进行说明。在第一个程序中,我们将使用外部用户定义的函数,在第二个程序中,我们将使用内部库函数来实现逻辑。

语法

func Compare(s1, s2 string) int

Compare() 函数用于比较给定的字符串,在Go中存在于strings包中。该函数将待比较的字符串作为参数传递给函数,并在比较两个字符串后返回整数等价值。返回的整数值可以是0、1或-1。如果两个字符串相等,则为0,如果第一个字符串大于第二个字符串,则为1,如果第二个字符串大于第一个字符串,则为-1。

步骤

步骤1 − 首先,我们导入fmt和strings包。String包允许我们使用预定义的字符串方法。

步骤2 − 然后,我们必须启动main函数。现在初始化两个字符串并将值存储在它们中。

步骤3 − 在屏幕上打印字符串。

步骤4 − 通过将用户输入的字符串值作为参数传递给它,调用strings.Compare()函数。

步骤5 − 将函数返回的数字存储在不同的变量中。

步骤6 − 使用条件语句来比较两个字符串的函数返回值。

步骤7 − 使用fmt.Println()函数在屏幕上打印相应的结果。

步骤8 − 通过使用不同的值将上述过程重复。

示例

在此程序中,我们将编写一个Go程序,使用库函数count来比较两个字符串。为了比较两个字符串,我们选择了count()和if-else条件语句的组合。

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")
   }
}

输出

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

结论

我们成功地编译并执行了使用库函数和示例来比较数字和字符串的Go语言程序。在这个示例中,我们使用了strings包中的compare()函数来比较两个字符串的字符。该函数会返回一个整数值,我们可以根据条件使用条件语句打印结果。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程