漢字
在 Golang 中,如果字符串中出現(xiàn)中文字符不能直接調(diào)用 len 函數(shù)來(lái)統(tǒng)計(jì)字符串字符長(zhǎng)度,這是因?yàn)樵?Go 中,字符串是以 UTF-8 為格式進(jìn)行存儲(chǔ)的,在字符串上調(diào)用 len 函數(shù),取得的是字符串包含的 byte 的個(gè)數(shù)。
每個(gè)中文字,占3個(gè)byte。英文字符,占一個(gè)byte。
str1 := "你好啊H"
fmt.Println(len(str1)) // 打印結(jié)果:10
func TestFunc2(t *testing.T) {
const nihongo = "你好呀"
for index, runeValue := range nihongo {
fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
}
//%#U,這個(gè)格式,即打印Unicode
//U+4F60 '你' starts at byte position 0
//U+597D '好' starts at byte position 3
//U+5440 '呀' starts at byte position 6
}
如何計(jì)算漢字的長(zhǎng)度呢?
func TestFunc2(t *testing.T) {
const nihongo = "你好呀"
for index, runeValue := range nihongo {
fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
}
//%#U,這個(gè)格式,即打印Unicode
//U+4F60 '你' starts at byte position 0
//U+597D '好' starts at byte position 3
//U+5440 '呀' starts at byte position 6
fmt.Printf("長(zhǎng)度:=%d \n", utf8.RuneCountInString(nihongo))
// 或者
fmt.Printf("長(zhǎng)度:=%d \n", len([]rune(nihongo)))
}
ASCII 字符串長(zhǎng)度使用 len() 函數(shù)。
Unicode 字符串長(zhǎng)度使用 utf8.RuneCountInString() 函數(shù)。
全角字符串轉(zhuǎn)換半角字符串
// 全角字符串轉(zhuǎn)換半角字符串
// 參數(shù):
// str:字符串
// 返回:
// 轉(zhuǎn)換半角后的字符串
func FullWidthStrToHalfWidthStr(str string) (result string) {
for _, charCode := range str {
inside_code := charCode
if inside_code == 12288 {
inside_code = 32
} else {
inside_code -= 65248
}
if inside_code < 32 || inside_code > 126 {
result += string(charCode)
} else {
result += string(inside_code)
}
}
return result
}
全角字符從unicode編碼從65281~65374
半角字符從unicode編碼從 33~126
空格比較特殊,全角為 12288,半角為 32
而且除空格外,全角/半角按unicode編碼排序在順序上是對(duì)應(yīng)的
所以可以直接通過(guò)用+-法來(lái)處理非空格數(shù)據(jù),對(duì)空格單獨(dú)處理
全角指的是一個(gè)字符占2個(gè)標(biāo)準(zhǔn)字符的位置(例如中國(guó)漢字)。
半角指的是占1個(gè)標(biāo)準(zhǔn)字符的位置(例如普通的字符a)。ASCII以內(nèi)的就叫半角符號(hào),以外的就叫全角符號(hào)。
注意:
并不是所有的全角字符都能被轉(zhuǎn)換為半角字符,例如漢字是全角字符,占2個(gè)字符的位置,但它無(wú)法被轉(zhuǎn)換;只有英文字母、數(shù)字鍵、符號(hào)鍵等才能可以做全角和半角之間的轉(zhuǎn)換。