File tree 2 files changed +46
-2
lines changed
2 files changed +46
-2
lines changed Original file line number Diff line number Diff line change 1
1
package main
2
2
3
- // interface define 元音
3
+ import (
4
+ "fmt"
5
+ )
6
+
7
+ // interface define 元音,接口中只能定义方法哦
4
8
type VowelsFinder interface {
5
9
FindVowels () []rune
6
10
}
7
11
8
- func main () {
12
+ type MyString string
9
13
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 ())
10
30
}
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments