developer tip

GoLang에서 문자열을 어떻게 비교합니까?

optionbox 2020. 11. 5. 07:55
반응형

GoLang에서 문자열을 어떻게 비교합니까?


Go 문자열 비교와 관련하여 '진정한'결과를 생성 할 수 없습니다. 문제를 설명하기 위해 다음을 작성하고 출력 스크린 샷을 첨부했습니다.

// string comparison in Go
package main
import "fmt"
import "bufio"
import "os"

func main() {
    var isLetterA bool 

    fmt.Println("Enter the letter a")
    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

    if(input == "a") {
        isLetterA = true
    } else {
        isLetterA = false 
    }

    fmt.Println("You entered",input)
    fmt.Println("Is it the letter a?",isLetterA)

}

예


==Go에서 문자열을 비교하는 올바른 연산자입니다. 그러나, 문자열은 당신과 함께 STDIN에서 읽어 reader.ReadString포함되어 있지 않습니다 "a"만, "a\n"(당신이 자세히 본다면, 당신은 당신의 예제 출력에서 여분의 줄 바꿈을 볼 수 있습니다).

strings.TrimRight함수를 사용 하여 입력에서 후행 공백을 제거 할 수 있습니다 .

if strings.TrimRight(input, "\n") == "a" {
    // ...
}

플랫폼 독립 사용자 또는 Windows 사용자의 경우 수행 할 수있는 작업은 다음과 같습니다.

가져 오기 런타임 :

import (
    "runtime"
    "strings"
)

그런 다음 다음과 같이 문자열을 다듬습니다.

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")
}

이제 다음과 같이 비교할 수 있습니다.

if strings.Compare(input, "a") == 0 {
  //....yourCode
}

여러 플랫폼에서 STDIN을 사용할 때 더 나은 접근 방식입니다.

설명

This happens because on windows lines end with "\r\n" which is known as CRLF, but on UNIX lines end with "\n" which is known as LF and that's why we trim "\n" on unix based operating systems while we trim "\r\n" on windows.


The content inside strings in Golang can be compared using == operator. If the results are not as expected there may be some hidden characters like \n, \r, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings package in golang.

For Instance, spaces can be removed using strings.TrimSpace function. You can also define a custom function to remove any character you need. strings.TrimFunc function can give you more power.

참고 URL : https://stackoverflow.com/questions/34383705/how-do-i-compare-strings-in-golang

반응형