From 30b377189b56e52a90888af94718de000ddc1d14 Mon Sep 17 00:00:00 2001 From: Tinywan <756684177@qq.com> Date: Sat, 25 Aug 2018 18:02:27 +0800 Subject: [PATCH] =?UTF-8?q?Unicode=E5=92=8CUTF-8=E4=B9=8B=E9=97=B4?= =?UTF-8?q?=E7=9A=84=E5=85=B3=E7=B3=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/interface/demo01.go | 24 ++++++++++++++++++++++-- demo/string/rune01.go | 24 ++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 demo/string/rune01.go diff --git a/demo/interface/demo01.go b/demo/interface/demo01.go index 6187199..38e5642 100644 --- a/demo/interface/demo01.go +++ b/demo/interface/demo01.go @@ -1,10 +1,30 @@ package main -// interface define 元音 +import ( + "fmt" +) + +// interface define 元音,接口中只能定义方法哦 type VowelsFinder interface { FindVowels() []rune } -func main() { +type MyString string +// 方法 +func (ms MyString) FindVowels() []rune { + var vowels []rune + for _, rune := range ms { + if rune == 'a' || rune == 'e' || rune == 'i' || rune == 'o' || rune == 'u' { + vowels = append(vowels, rune) + } + } + return vowels +} + +func main() { + name := MyString("Sam Anderson") + var v VowelsFinder + v = name + fmt.Printf("Vowels are %c", v.FindVowels()) } diff --git a/demo/string/rune01.go b/demo/string/rune01.go new file mode 100644 index 0000000..27925f6 --- /dev/null +++ b/demo/string/rune01.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "unicode/utf8" +) + +func main() { + s := "hello 你好" // 8 = 5个字符 + 1个空格 + 2个汉字 + fmt.Println("len(s):", len(s)) // len(s): 12 + + var str = "hello 你好" + + //golang中string底层是通过byte数组实现的,直接求len 实际是在按字节长度计算 所以一个汉字占3个字节算了3个长度 + fmt.Println("len(str):", len(str)) + + //以下两种都可以得到str的字符串长度 + + //golang中的unicode/utf8包提供了用utf-8获取长度的方法 + fmt.Println("RuneCountInString:", utf8.RuneCountInString(str)) + + // 通过rune类型处理unicode字符 + fmt.Println("rune:", len([]rune(str))) +}