本篇文章說明兩個 package 的部分函式,strings package 和 strconv package
strings package
Official Document
ToUpper
1 2 3
| func ToUpper(s string) string
strings.ToUpper("Gopher")
|
ToLower
1 2 3
| func ToLower(s string) string
strings.ToLower("Gopher")
|
Replace
1 2 3 4
| func Replace(s, old, new string, n int) string
strings.Replace("oink oink oink", "k", "ky", 2) strings.Replace("oink oink oink", "oink", "moo", -1)
|
Split
1 2 3 4 5 6
| func Split(s, sep string) []string
strings.Split("a,b,c", ",") strings.Split("a man a plan a canal panama", "a ") strings.Split(" xyz ", "") strings.Split("", "Bernardo O'Higgins")
|
strconv package
Official Document
ParseInt and Atoi
1 2 3 4 5
| func ParseInt(s string, base int, bitSize int) (i int64, err error)
if s, err := strconv.ParseInt("16", 10, 32); err == nil { fmt.Printf("%T, %v\n", s, s) }
|
Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.
1 2 3
| func Atoi(s string) (int, error)
s, err := strconv.Atoi("10");
|
ParseFloat
1 2 3 4 5 6 7 8 9
| func ParseFloat(s string, bitSize int) (float64, error)
if s, err := strconv.ParseFloat("3.1415926535", 32); err == nil { fmt.Printf("%T, %v\n", s, s) }
if s, err := strconv.ParseFloat(v, 64); err == nil { fmt.Printf("%T, %v\n", s, s) }
|
ParseBool
It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.
1 2 3
| func ParseBool(str string) (bool, error)
s, err := strconv.ParseBool("true");
|
Itoa
1 2 3
| func Itoa(i int) string
s := strconv.Itoa(10)
|
Contains
1 2 3 4
| func Contains(s, substr string) bool
strings.Contains("seafood", "foo") strings.Contains("seafood", "bar")
|