English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang 기본 튜토리얼

Golang 제어 문

Golang 함수 & 메서드

Golang 구조체

Golang 슬라이스 & 배열

Golang 문자열(String)

Golang 포인터

Golang 인터페이스

Golang 병행

Golang 예외(Error)

Golang 다른杂项

Go 문자열 비교

Go 언어에서 문자열은 UTF-8编码된 불변의 임의의 바이트 링크. 문자열을 비교하는 데 두 가지 다른 방법을 사용할 수 있습니다:

1. 비교 연산자를 사용하면문자열이 비교 연산자를 지원하는 것으로 이동합니다. 즉==, !=, >=, <=, <, >여기서==!=연산자는 주어진 문자열이 같은지 확인하는 데 사용됩니다. >=, <=, <, > 연산자는 레퍼런스 순서를 찾는 데 사용됩니다. 이 연산자의 결과는 부울형이며, 조건이 만족되면 반환됩니다.true아니면 반환false

문자열의 ==과 != 연산자 예제1:

//문자열의 ==과 != 연산자
package main
import "fmt"
func main() {
    //문자열 생성 및 초기화
    //단축 선언 사용
    str1 := "Geeks"
    str2 := "Geek"
    str3 := "w3codebox"
    str4 := "Geeks"
    //문자열이 같을지 확인
    //사용 == 연산자
    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)
    //문자열이 다를지 확인
    //사용 !!= 연산자
    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

문자열 비교 연산자 예제2:

//문자열 비교 연산자
package main 
  
import "fmt"
  
func main() { 
  
        //생성 및 초기화
        //단축 선언 사용
    myslice := []string{"Geeks", "Geeks", 
                    "gfg", "GFG", "for"} 
      
    fmt.Println("Slice: ", myslice) 
  
    //비교 연산자 사용
    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.useCompare() 메서드를 사용하면:또한 문자열 패키지에서 제공하는 내장 함수 Compare()를 사용하여 두 문자열을 비교할 수 있습니다. 두 문자열을 비교한 후 이 함수는 정수 값을 반환합니다. 반환 값은 다음과 같습니다:

  • 만약str1 == str2,그렇다면 0을 반환합니다 。

  • 만약str1> str2,반환1 。

  • 만약str1 <str2,반환-1 。

문법:

func Compare(str1, str2 string) int
//문자열을 compare() 함수로 사용
package main 
  
import ( 
    "fmt"
    "strings"
) 
  
func main() { 
  
    //문자열을 비교하는 데 비교 함수 사용
    fmt.Println(strings.Compare("gfg", "Geeks")) 
      
    fmt.Println(strings.Compare("w3codebox", "w3codebox")) 
      
    fmt.Println(strings.Compare("Geeks", " GFG")) 
      
    fmt.Println(strings.Compare("GeeKS", "GeeKs")) 
}

출력:

1
0
1
-1