Go语言学习之strings包(the way to go)

来源:互联网 发布:企业网站seo教程 编辑:程序博客网 时间:2024/05/20 19:46

生命不止,继续 go go go !!!

今天跟大家分享的是stirngs包,为我们提供了一些方便的字符串操作。这里需要注意一下,不引入strings包同样是可以使用string定义变量的。

之前的博客结果过string的用法:
Go语言学习之字符串(The way to go)

import “strings”
官方描述:
Package strings implements simple functions to manipulate UTF-8 encoded strings.

看到了吧,是UTF-8编码的字符串。

注意是看一些方法:

转换相关的方法

func ToUpper(s string) stringfunc ToLower(s string) stringfunc ToTitle(s string) stringfunc ToUpperSpecial(_case unicode.SpecialCase, s string) stringfunc ToLowerSpecial(_case unicode.SpecialCase, s string) stringfunc ToTitleSpecial(_case unicode.SpecialCase, s string) stringfunc Title(s string) string

例子:

package mainimport (    "fmt"    "strings"    "unicode")func main() {    var s string = "Welcome to The WORld of go!"    fmt.Println(s)    upper_s := strings.ToUpper(s)    fmt.Println(upper_s)    lower_s := strings.ToLower(s)    fmt.Println(lower_s)    title_s := strings.ToTitle(s)    fmt.Println(title_s)    var SC unicode.SpecialCase    fmt.Println(strings.ToUpperSpecial(SC, s))    fmt.Println(strings.ToLowerSpecial(SC, s))    fmt.Println(strings.ToTitleSpecial(SC, s))}

输出:
Welcome to The WORld of go!
WELCOME TO THE WORLD OF GO!
welcome to the world of go!
WELCOME TO THE WORLD OF GO!
WELCOME TO THE WORLD OF GO!
welcome to the world of go!
WELCOME TO THE WORLD OF GO!

比较相关的方法

func Compare(a, b string) intfunc EqualFold(s, t string) bool

例子:

package mainimport (    "fmt"    "strings")func main() {    var s1 string = "Welcome to The WORld of go!"    var s2 string = "Welcome go The WORld of go!"    fmt.Println(strings.Compare(s1, s2)) // s1 > s2 返回值为int型,1    fmt.Println(strings.EqualFold("Go", "go")) //返回值为bool型, true}

输出:
1
true

清理裁剪相关的方法

func Trim(s string, cutset string) stringfunc TrimLeft(s string, cutset string) stringfunc TrimRight(s string, cutset string) stringfunc TrimFunc(s string, f func(rune) bool) stringfunc TrimLeftFunc(s string, f func(rune) bool) stringfunc TrimRightFunc(s string, f func(rune) bool) stringfunc TrimSpace(s string) stringfunc TrimPrefix(s, prefix string) stringfunc TrimSuffix(s, suffix string) string

例子:

package mainimport (    "fmt"    "strings")func main() {    var s = "Goodbye, world!"    fmt.Println(strings.Trim(s, "!"))    fmt.Println(strings.TrimRight(s, "!"))    fmt.Println(strings.TrimLeft(s, "!"))    fmt.Println(strings.TrimPrefix(s, "Go"))    fmt.Println(strings.TrimSuffix(s, "d!"))    fmt.Println(strings.TrimSpace(s))    fmt.Println(strings.TrimPrefix(s, "Goodbye,"))    fmt.Println(strings.TrimPrefix(s, "Howdy,"))}

输出:
Goodbye, world
Goodbye, world
Goodbye, world!
odbye, world!
Goodbye, worl
Goodbye, world!
world!
Goodbye, world!

拆分、合并相关的方法

func Split(s, sep string) []stringfunc SplitN(s, sep string, n int) []stringfunc SplitAfter(s, sep string) []stringfunc SplitAfterN(s, sep string, n int) []stringfunc Fields(s string) []stringfunc FieldsFunc(s string, f func(rune) bool) []stringfunc Join(a []string, sep string) stringfunc Repeat(s string, count int) string

例子:

package mainimport (    "fmt"    "strings"    "unicode")func main() {    fmt.Printf("%q\n", strings.Split("a,b,c", ",")) //根据,进行拆分,返回的是[]string    fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))    fmt.Printf("%q\n", strings.Split(" xyz ", ""))    fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))    fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 2))    z := strings.SplitN("a,b,c", ",", 0)    fmt.Printf("%q (nil = %v)\n", z, z == nil)    fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ","))    fmt.Printf("%q\n", strings.SplitAfterN("a,b,c", ",", 2))    fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))    f := func(c rune) bool {        return !unicode.IsLetter(c) && !unicode.IsNumber(c)    }    fmt.Printf("Fields are: %q", strings.FieldsFunc("  foo1;bar2,baz3...", f))    s := []string{"foo", "bar", "baz"}    fmt.Println(strings.Join(s, ", ")) //连接    fmt.Println("ba" + strings.Repeat("na", 2)) //重复}

输出:
[“a” “b” “c”]
[“” “man ” “plan ” “canal panama”]
[” ” “x” “y” “z” ” “]
[“”]
[“a” “b,c”]
[] (nil = true)
[“a,” “b,” “c”]
[“a,” “b,c”]
Fields are: [“foo” “bar” “baz”]Fields are: [“foo1” “bar2” “baz3”]
foo, bar, baz
banana

子字符串相关的方法

func HasPrefix(s, prefix string) boolfunc HasSuffix(s, suffix string) boolfunc Contains(s, substr string) boolfunc ContainsRune(s string, r rune) boolfunc ContainsAny(s, chars string) boolfunc Index(s, sep string) intfunc IndexByte(s string, c byte) intfunc IndexRune(s string, r rune) intfunc IndexAny(s, chars string) intfunc IndexFunc(s string, f func(rune) bool) intfunc LastIndex(s, sep string) intfunc LastIndexByte(s string, c byte) intfunc LastIndexAny(s, chars string) intfunc LastIndexFunc(s string, f func(rune) bool) intfunc Count(s, sep string) int

例子:

package mainimport (    "fmt"    "strings")func main() {    s := "hello go world"    fmt.Println(strings.HasPrefix(s, "hell"))    fmt.Println(strings.HasSuffix(s, "world"))    fmt.Println(strings.Contains(s, "hell"))    fmt.Println(strings.ContainsAny(s, "ad"))    fmt.Println(strings.Index(s, "o"))    fmt.Println(strings.LastIndex(s, "o"))    fmt.Println(strings.IndexByte(s, 'o'))    fmt.Println(strings.LastIndexByte(s, 'o'))    fmt.Println(strings.IndexAny(s, "ow"))    fmt.Println(strings.LastIndexAny(s, "ow"))    fmt.Println(strings.Count(s, "o"))}

输出:
true
true
true
true
4
10
4
10
4
10
3

替换相关的方法

func Replace(s, old, new string, n int) stringfunc Map(mapping func(rune) rune, s string) string

例子:

package mainimport (    "fmt"    "strings")func main() {    value := "Your cat is cute"    fmt.Println(value)    result := strings.Replace(value, "cat", "dog", -1)    fmt.Println(result)    value = "bird bird bird"    result = strings.Replace(value, "bird", "fish", 1)    fmt.Println(result)    rot13 := func(r rune) rune {        switch {        case r >= 'A' && r <= 'Z':            return 'A' + (r-'A'+13)%26        case r >= 'a' && r <= 'z':            return 'a' + (r-'a'+13)%26        }        return r    }    fmt.Println(strings.Map(rot13, "'Twas brillig and the slithy gopher..."))}

输出:
Your cat is cute
Your dog is cute
fish bird bird
‘Gjnf oevyyvt naq gur fyvgul tbcure…

其他方法

type Reader struct { ... }func NewReader(s string) *Readerfunc (r *Reader) Read(b []byte) (n int, err error)func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)func (r *Reader) WriteTo(w io.Writer) (n int64, err error)func (r *Reader) Seek(offset int64, whence int) (int64, error)func (r *Reader) ReadByte() (byte, error)func (r *Reader) UnreadByte() errorfunc (r *Reader) ReadRune() (ch rune, size int, err error)func (r *Reader) UnreadRune() errorfunc (r *Reader) Len() intfunc (r *Reader) Size() int64func (r *Reader) Reset(s string)type Replacer struct { ... }func NewReplacer(oldnew ...string) *Replacerfunc (r *Replacer) Replace(s string) stringfunc (r *Replacer) WriteString(w io.Writer, s string) (n int, err error)

应用
拆分host和端口号
不像Python那样直接返回,需要自己处理一下:

package mainimport (    "fmt"    "strings")func main() {    s := strings.Split("127.0.0.1:5432", ":")    ip, port := s[0], s[1]    fmt.Println(ip, port)}

或者使用net包:

package mainimport (    "fmt"    "net")func main() {    host, port, err := net.SplitHostPort("127.0.0.1:5432")    fmt.Println(host, port, err)}

这里写图片描述

原创粉丝点击