我正在創建一個數據結構來存儲單個Unicode字符,然後我可以對其進行比較。在golang中存儲unicode字符
兩個問題:
應怎樣使用的數據類型?
type ds struct { char Char // What should Char be so that I can safely compare two ds? }
我需要一種方法來比較任意兩個Unicode字符串的第一個字符。有沒有簡單的方法來做到這一點?基本上,我如何檢索字符串的第一個Unicode字符?
我正在創建一個數據結構來存儲單個Unicode字符,然後我可以對其進行比較。在golang中存儲unicode字符
兩個問題:
應怎樣使用的數據類型?
type ds struct { char Char // What should Char be so that I can safely compare two ds? }
我需要一種方法來比較任意兩個Unicode字符串的第一個字符。有沒有簡單的方法來做到這一點?基本上,我如何檢索字符串的第一個Unicode字符?
像這樣:type Char rune
。
注意「比較」,這是一個複雜的事情與Unicode。儘管代碼點(rune
s)很容易在數字上比較(U + 0020 == U + 0020; U + 1234 < U + 2345),但這可能是也可能不是您想要的情況,即組合字符和Unicode提供的其他內容。
然後我如何訪問unicode字符串的第一個符文? –
unicode/utf8.DecodeRune [InString]:https://golang.org/pkg/unicode/utf8/#DecodeRune和DecodeRuneInString – Volker
要比較utf8字符串,您需要檢查它們的符文值。 Runevalue是utf8字符的int32值。使用標準包「unicode/utf8」。通過「串[0:]」來獲得的第一個字符
test := "春節"
runeValue, width := utf8.DecodeRuneInString(test[0:])
fmt.Println(runeValue,width)
fmt.Printf("%#U %d", runeValue, runeValue)
現在你可以使用==操作符
你也需要存儲字符串比較兩個字符串的第一個字符的runeValue在字符串中如果你想存儲整個字符。
type ds struct {
char string // What should Char be so that I can safely compare two ds?
}
完整的代碼演示此:
package main
import (
"fmt"
"unicode/utf8"
)
type ds struct {
char string // What should Char be so that I can safely compare two ds?
}
func main() {
fmt.Println("Hello, playground")
ds1 := ds{"春節"}
ds2 := ds{"春節"}
runeValue1, _ := utf8.DecodeRuneInString(ds1.char[0:])
runeValue2, _ := utf8.DecodeRuneInString(ds2.char[0:])
fmt.Printf("%#U %#U", runeValue1, runeValue2)
if runeValue1 == runeValue2 {
fmt.Println("\nFirst Char Same")
} else {
fmt.Println("\nDifferent")
}
}
從VOLKERS,答案,我們可以只使用符文來比較。
type Char rune
[]rune(str)[0]
你不需要輸入字符符文。除非你正在做[] Char(str)[0] – khrm
現在我已經給出完整的代碼演示這一點。 – khrm