go标准库的学习-strings-字符串操作

参考https://studygolang.com/pkgdoc

导入方式:

import "strings"

strings包实现了用于操作字符的简单函数。

 

常用的几个函数:

func Contains

func Contains(s, substr string) bool

判断字符串s是否包含子串substr。

举例:

package main 
import(
    "fmt"
    "strings"

)

func main() {
    fmt.Println(strings.Contains("seafood", "foo")) //true
    fmt.Println(strings.Contains("seafood", "bar")) //false
    fmt.Println(strings.Contains("seafood", "")) //true
    fmt.Println(strings.Contains("", "")) //true
}

 

func Index

func Index(s, sep string) int

子串sep在字符串s中第一次出现的位置,不存在则返回-1。

举例:

package main 
import(
    "fmt"
    "strings"

)

func main() {
    fmt.Println(strings.Index("chicken", "ken")) //4
    fmt.Println(strings.Index("chicken", "dmr")) //-1
}

 

func Join

func Join(a []string, sep string) string

将一系列字符串连接为一个字符串,之间用sep来分隔。

举例:

package main 
import(
    "fmt"
    "strings"

)

func main() {
    s := []string{"foo", "bar", "baz"}
    fmt.Println(strings.Join(s, ", "))//foo, bar, baz
}

 

func Repeat

func Repeat(s string, count int) string

返回count个s串联的字符串。

举例:

package main 
import(
    "fmt"
    "strings"

)

func main() {
    fmt.Println("ba" + strings.Repeat("na", 2)) //banana
}

 

func Replace

func Replace(s, old, new string, n int) string

返回将s中前n个不重叠old子串都替换为new的新字符串,如果n<0会替换所有old子串。

举例:

package main 
import(
    "fmt"
    "strings"

)

func main() {
    fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2)) //oinky oinky oink
    fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1)) //moo moo moo
}

 

func Split

func Split(s, sep string) []string

用去掉s中出现的sep的方式进行分割,会分割到结尾,并返回生成的所有片段组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个字符串。

举例:

package main 
import(
    "fmt"
    "strings"

)

func main() {
    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 Trim

func Trim(s string, cutset string) string

返回将s前后端所有cutset包含的utf-8码值都去掉的字符串。

举例:

package main 
import(
    "fmt"
    "strings"

)

func main() {
    fmt.Printf("[%q]\n", strings.Trim(" !!! Achtung! Achtung! !!! ", "! ")) //["Achtung! Achtung"]
}

 

func Fields

func Fields(s string) []string

返回将字符串按照空白(unicode.IsSpace确定,可以是一到多个连续的空白字符)分割的多个字符串。如果字符串全部是空白或者是空字符串的话,会返回空切片。

举例:

package main 
import(
    "fmt"
    "strings"

)

func main() {
    fmt.Printf("Fields are: %q\n", strings.Fields("  foo bar  baz   ")) //Fields are: ["foo" "bar" "baz"]
}

 

)type Reader

type Reader struct {
    s        string
    i        int64 // current reading index
    prevRune int   // index of previous rune; or < 0

Reader类型通过从一个字符串读取数据,实现了io.Reader、io.Seeker、io.ReaderAt、io.WriterTo、io.ByteScanner、io.RuneScanner接口。

实现源码:

1> func NewReader

func NewReader(s string) *Reader

NewReader创建一个从s读取数据的Reader。本函数类似bytes.NewBufferString,但是更有效率,且为只读的。

该初始化源码:

func NewReader(s string) *Reader { return &Reader{s, 0, -1} }

举例:

package main 
import(
    "fmt"
    "io"
    "strings"
    "os"
)
func main() {
    reader := strings.NewReader("test reader's usage")
    buf := make([]byte, 4) //生成一个能够存放4 bytes数据的数组
    for {//无限循环直至有错或数据读取完返回EOF
        count, err := reader.Read(buf)//后面读取的内容会覆盖前面的buf的内容
        if err != nil {
            if err == io.EOF {
                fmt.Println("EOF : ", count)
                break
            }
            fmt.Println(err)
            os.Exit(1)
        }
        fmt.Println(count, string(buf[:count]))
    }
}

返回:

userdeMBP:src user$ go run test.go
4 test
4  rea
4 der'
4 s us
3 age
EOF :  0

 

2》func (*Reader) Len

func (r *Reader) Len() int

Len返回r包含的字符串还没有被读取的部分,即当前文件指针之后的内容

3》func (*Reader) Read

func (r *Reader) Read(b []byte) (n int, err error)

4》func (*Reader) ReadByte

func (r *Reader) ReadByte() (b byte, err error)

5》func (*Reader) UnreadByte

func (r *Reader) UnreadByte() error

6》func (*Reader) ReadRune

func (r *Reader) ReadRune() (ch rune, size int, err error)

7》func (*Reader) UnreadRune

func (r *Reader) UnreadRune() error

8》func (*Reader) ReadAt

func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)

9》func (*Reader) WriteTo

func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

WriteTo实现了io.WriterTo接口。

举例:

package main 
import(
    "fmt"
    "strings"
    "log"
    "os"
)
func main() {
    fmt.Println("1 - test Read")
    reader := strings.NewReader("test strings's NewReader() and the usage of its function\n")
    len := reader.Len() 
    fmt.Printf("1 before - the length of the part have not beed read : %d\n", len)
    data := make([]byte, 8)
    number, err := reader.Read(data)
    if err != nil {
        log.Fatal(err)
    }
    len = reader.Len() 
    fmt.Printf("1 after - the length of the part have not beed read : %d\n", len)
    fmt.Println(string(data[:number]))

    fmt.Println("2 - test ReadByte")
    for i := 0; i < 3; i++ {
        readbyte, err := reader.ReadByte()//从当前文件指针向后读取一个byte的内容
        if err != nil {
            log.Fatal(err)
        }
        fmt.Print(readbyte, " ")    
    }
    fmt.Println()

    len = reader.Len() 
    fmt.Printf("2 after - the length of the part have not beed read : %d\n", len)

    fmt.Println("3 - test UnreadByte") //就相当于撤销之前的一次ReadByte()操作,文件指针向前移一位
    err = reader.UnreadByte()
    if err != nil {
        log.Fatal(err)
    }

    len = reader.Len() 
    fmt.Printf("3 after - the length of the part have not beed read : %d\n", len)

    fmt.Println("4 - test ReadAt")
    number1, err := reader.ReadAt(data, 11)
    if err != nil {
        log.Fatal(err)
    }
    len = reader.Len() 
    fmt.Printf("4 after - the length of the part have not beed read : %d\n", len)
    fmt.Println(string(data[:number1]))

    fmt.Println("5 - test ReadRune")
    for i := 0; i < 3; i++ {
        readrune, _, err := reader.ReadRune()//从当前文件指针向后读取一个rune的内容
        if err != nil {
            log.Fatal(err)
        }
        fmt.Print(readrune, " ")    
        // fmt.Print(readrune)    
    }
    fmt.Println()

    len = reader.Len() 
    fmt.Printf("5 after - the length of the part have not beed read : %d\n", len)

    fmt.Println("6 - test UnreadRune")
    err = reader.UnreadRune() //就相当于撤销之前的一次ReadByte()操作,文件指针向前移一位
    if err != nil {
        log.Fatal(err)
    }
    len = reader.Len() 
    fmt.Printf("6 after - the length of the part have not beed read : %d\n", len)

    fmt.Println("test WriterTo")
    number3, err := reader.WriteTo(os.Stdout)//从当前指针开始将文件内容输出到os.Stdout,即标准输出中
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(number3)
}

返回:

userdeMBP:src user$ go run test.go
1 - test Read
1 before - the length of the part have not beed read : 57
1 after - the length of the part have not beed read : 49
test str
2 - test ReadByte
105 110 103  //即ing
2 after - the length of the part have not beed read : 46
3 - test UnreadByte
3 after - the length of the part have not beed read : 47
4 - test ReadAt
4 after - the length of the part have not beed read : 47
s's NewR
5 - test ReadRune
103 115 39  //即gs'
5 after - the length of the part have not beed read : 44
6 - test UnreadRune
6 after - the length of the part have not beed read : 45
test WriterTo
's NewReader() and the usage of its function
45

 未完待续

posted @ 2019-02-28 23:05  慢行厚积  阅读(1036)  评论(0编辑  收藏  举报