1. 程式人生 > >golang語言漸入佳境[23]-string分割類函式

golang語言漸入佳境[23]-string分割類函式

string分割類函式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main

import (
"fmt"
"strings"
"unicode"
)

/*
1、func Fields(s string) []string
將字串s以空白字元分割,返回一個切片

2、func FieldsFunc(s string, f func(rune) bool) []string
將字串s以滿足f(r)==true的字元分割,返回一個切片


3、func Split(s, sep string) []string
將字串s以sep作為分隔符進行分割,分割後字元最後去掉sep

4、func SplitAfter(s, sep string) []string
將字串s以sep作為分隔符進行分割,分割後字元最後附上sep

5、func SplitAfterN(s, sep string, n int) []string
將字串s以sep作為分隔符進行分割,分割後字元最後附上sep,n決定返回的切片數

6、func SplitN(s, sep string, n int) []string
將字串s以sep作為分隔符進行分割,分割後字元最後去掉sep,n決定返回的切片數

*/

func main() {
TestSplitAfterN()
}

func TestFields() {
fmt.Println(strings.Fields("  abc 123 ABC xyz XYZ")) //[abc 123 ABC xyz XYZ]
}

func TestFieldsFunc() {
f := func(c rune) bool {
//return c == '='
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
fmt.Println(strings.FieldsFunc("[email protected]
*ABC&xyz%XYZ"
, f)) //[abc 123 ABC xyz XYZ]

}

func TestSplit() {
fmt.Printf("%q\n", strings.Split("a,b,c", ","))//[a b c]
fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))//["" "man " "plan " "canal panama"]
fmt.Printf("%q\n", strings.Split(" xyz ", ""))//[" " "x" "y" "z" " "]
fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))//[""]
}

func TestSplitN() {
fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 2))//["a"   "b,c"]
fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 1))//["a,b,c"]
}

func TestSplitAfter() {
fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ","))//["a," "b," "c"]
}

func TestSplitAfterN() {
fmt.Printf("%q\n", strings.SplitAfterN("a,b,c", ",", 2))//["a,"   "b,c"]
}

image.png