码迷,mamicode.com
首页 > 其他好文 > 详细

[笔记] Golang String

时间:2016-05-05 00:42:14      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "strconv"
 6     "strings"
 7 )
 8 
 9 func main() {
10     // strings demo
11     Contains()
12     Join()
13     Index()
14     Repeat()
15     Replace()
16     Split()
17 
18     // strconv demo
19     AppendDemo()
20     FormatDemo()
21     ParseDemo()
22 }
23 
24 func Contains() {
25     fmt.Println(strings.Contains("seafood", "foo")) //true
26     fmt.Println(strings.Contains("seafood", "bar")) //false
27 }
28 
29 func Join() {
30     s := []string{"foo", "bar", "baz"}
31     fmt.Println(strings.Join(s, ",")) // foo,bar,baz
32 }
33 
34 func Index() {
35     fmt.Println(strings.Index("chicken", "ken")) // 4
36     fmt.Println(strings.Index("chicken", "dmr")) // -1
37 }
38 
39 func Repeat() {
40     fmt.Println("ba" + strings.Repeat("na", 2)) // banana
41 }
42 
43 func Replace() {
44     fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))      // oinky oinky oink
45     fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1)) // moo moo moo
46 }
47 
48 func Split() {
49     fmt.Printf("%q\n", strings.Split("a,b,c", ","))                        //["a" "b" "c"]
50     fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a ")) //["" "man " "plan " "canal panama"]
51     fmt.Printf("%q\n", strings.Split(" xyz ", ""))                         //[" " "x" "y" "z" " "]
52     fmt.Printf("%q\n", strings.Split("", "Bernardo O‘Higgins"))            //[""]
53 }
54 
55 func AppendDemo() {
56     str := make([]byte, 0, 100)
57     str = strconv.AppendInt(str, 4567, 10)
58     str = strconv.AppendBool(str, false)
59     str = strconv.AppendQuote(str, "abcdefg")
60     str = strconv.AppendQuoteRune(str, )
61     fmt.Println(string(str)) //4567false"abcdefg"‘
62 }
63 
64 func FormatDemo() {
65     a := strconv.FormatBool(false)
66     b := strconv.FormatFloat(123.23, g, 12, 64)
67     c := strconv.FormatInt(1234, 10)
68     d := strconv.FormatUint(12345, 10)
69     e := strconv.Itoa(1023)
70     fmt.Println(a, b, c, d, e) // false 123.23 1234 12345 1023
71 }
72 
73 func ParseDemo() {
74     a, err := strconv.ParseBool("false")
75     handleErr(err)
76     b, err := strconv.ParseFloat("123,23", 64)
77     handleErr(err)
78     c, err := strconv.ParseInt("1234", 10, 64)
79     handleErr(err)
80     d, err := strconv.ParseUint("12345", 10, 64)
81     handleErr(err)
82     e := strconv.Itoa(1023)
83     handleErr(err)
84     fmt.Println(a, b, c, d, e) // false 0 1234 12345 1023
85 }
86 
87 func handleErr(err error) {
88     if err != nil {
89         fmt.Println(err)
90     }
91 }

 

[笔记] Golang String

标签:

原文地址:http://www.cnblogs.com/loveyx/p/5460274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!