Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 30b3771

Browse files
committed
Unicode和UTF-8之间的关系
1 parent fa2bc0b commit 30b3771

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

‎demo/interface/demo01.go‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,30 @@
11
package main
22

3-
// interface define 元音
3+
import (
4+
"fmt"
5+
)
6+
7+
// interface define 元音,接口中只能定义方法哦
48
type VowelsFinder interface {
59
FindVowels() []rune
610
}
711

8-
funcmain() {
12+
typeMyStringstring
913

14+
// 方法
15+
func (ms MyString) FindVowels() []rune {
16+
var vowels []rune
17+
for _, rune := range ms {
18+
if rune == 'a' || rune == 'e' || rune == 'i' || rune == 'o' || rune == 'u' {
19+
vowels = append(vowels, rune)
20+
}
21+
}
22+
return vowels
23+
}
24+
25+
func main() {
26+
name := MyString("Sam Anderson")
27+
var v VowelsFinder
28+
v = name
29+
fmt.Printf("Vowels are %c", v.FindVowels())
1030
}

‎demo/string/rune01.go‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"unicode/utf8"
6+
)
7+
8+
func main() {
9+
s := "hello 你好" // 8 = 5个字符 + 1个空格 + 2个汉字
10+
fmt.Println("len(s):", len(s)) // len(s): 12
11+
12+
var str = "hello 你好"
13+
14+
//golang中string底层是通过byte数组实现的,直接求len 实际是在按字节长度计算 所以一个汉字占3个字节算了3个长度
15+
fmt.Println("len(str):", len(str))
16+
17+
//以下两种都可以得到str的字符串长度
18+
19+
//golang中的unicode/utf8包提供了用utf-8获取长度的方法
20+
fmt.Println("RuneCountInString:", utf8.RuneCountInString(str))
21+
22+
// 通过rune类型处理unicode字符
23+
fmt.Println("rune:", len([]rune(str)))
24+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /