亚洲区国产区激情区无码区,国产成人mv视频在线观看,国产A毛片AAAAAA,亚洲精品国产首次亮相在线

Golang 菜鳥教程

Golang 控制語(yǔ)句

Golang 函數(shù) & 方法

Golang 結(jié)構(gòu)體

Golang 切片 & 數(shù)組

Golang 字符串(String)

Golang 指針

Golang 接口

Golang 并發(fā)

Golang 異常(Error)

Golang 其他雜項(xiàng)

Go 字符串比較

在Go語(yǔ)言中,字符串是使用UTF-8編碼編碼的不可變的任意字節(jié)鏈。您可以使用兩種不同的方式來(lái)比較字符串:

1.使用比較運(yùn)算符:轉(zhuǎn)到字符串支持比較運(yùn)算符,即==,!=,> =,<=,<,>。在這里,==!=運(yùn)算符用于檢查給定的字符串是否相等。和> =,<=,<,>操作符用于查找詞法順序。這些運(yùn)算符的結(jié)果為布爾類型,意味著如果條件滿足,則返回true,否則返回false

字符串的==和!=運(yùn)算符示例1:

//包含字符串的==和!=運(yùn)算符
package main

import "fmt"

func main() {

    //創(chuàng)建和初始化字符串
    //使用簡(jiǎn)寫聲明
    str1 := "Geeks"
    str2 := "Geek"
    str3 := "nhooo"
    str4 := "Geeks"

    //檢查字符串是否相等
    //使用==運(yùn)算符
    result1 := str1 == str2
    result2 := str2 == str3
    result3 := str3 == str4
    result4 := str1 == str4

    fmt.Println("Result 1: ", result1)
    fmt.Println("Result 2: ", result2)
    fmt.Println("Result 3: ", result3)
    fmt.Println("Result 4: ", result4)

    //檢查字符串是否不相等
    //使用!=運(yùn)算符
    result5 := str1 != str2
    result6 := str2 != str3
    result7 := str3 != str4
    result8 := str1 != str4

    fmt.Println("\nResult 5: ", result5)
    fmt.Println("Result 6: ", result6)
    fmt.Println("Result 7: ", result7)
    fmt.Println("Result 8: ", result8)

}

輸出:

Result 1:  false
Result 2:  false
Result 3:  false
Result 4:  true

Result 5:  true
Result 6:  true
Result 7:  true
Result 8:  false

字符串的比較運(yùn)算符示例2:

//字符串的比較運(yùn)算符
package main 
  
import "fmt"
  
func main() { 
  
        //創(chuàng)建和初始化
        //使用速記聲明
    myslice := []string{"Geeks", "Geeks", 
                    "gfg", "GFG", "for"} 
      
    fmt.Println("Slice: ", myslice) 
  
    //使用比較運(yùn)算符
    result1 := "GFG" > "Geeks"
    fmt.Println("Result 1: ", result1) 
  
    result2 := "GFG" < "Geeks"
    fmt.Println("Result 2: ", result2) 
  
    result3 := "Geeks" >= "for"
    fmt.Println("Result 3: ", result3) 
  
    result4 := "Geeks" <= "for"
    fmt.Println("Result 4: ", result4) 
  
    result5 := "Geeks" == "Geeks"
    fmt.Println("Result 5: ", result5) 
  
    result6 := "Geeks" != "for"
    fmt.Println("Result 6: ", result6) 
}

輸出:

Slice:  [Geeks Geeks gfg GFG for]
Result 1:  false
Result 2:  true
Result 3:  false
Result 4:  true
Result 5:  true
Result 6:  true

2.使用Compare()方法:您還可以使用字符串包提供的內(nèi)置函數(shù)Compare()比較兩個(gè)字符串。在比較兩個(gè)字符串后,此函數(shù)返回整數(shù)值。返回值為:

  • 如果str1 == str2,則返回0 。

  • 如果str1> str2,返回1 。

  • 如果str1 <str2,返回-1 。

語(yǔ)法:

func Compare(str1, str2 string) int
//字符串使用compare()函數(shù)
package main 
  
import ( 
    "fmt"
    "strings"
) 
  
func main() { 
  
    //比較字符串使用比較函數(shù)
    fmt.Println(strings.Compare("gfg", "Geeks")) 
      
    fmt.Println(strings.Compare("nhooo", "nhooo")) 
      
    fmt.Println(strings.Compare("Geeks", " GFG")) 
      
    fmt.Println(strings.Compare("GeeKS", "GeeKs")) 

}

輸出:

1
0
1
-1