共计 11086 个字符,预计需要花费 28 分钟才能阅读完成。
go version go1.10.3
Go 中的字符串用法,能够在 godoc.org 上查看语法和用法。
最简略的语法就是获取字符串中的子串
s := "hello world"
fmt.Println(s[1:3], s[0:])
一:查找
1、查找返回索引
godoc.org 上索引的办法
Index
func Index(s, substr string) int
Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.
阐明:返回子串 substr 在字符串 s 中第一次呈现的地位
如果找不到则返回 -1;如果 substr 为空,则返回 0
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
s := "hello h 世界!"
fmt.Println(strings.Index(s, "h"))
fmt.Println(strings.Index(s, "!"))
fmt.Println(strings.Index(s, "wo"))
}
//output:
//0
//14
//-1
IndexAny
func IndexAny(s, chars string) int
IndexAny returns the index of the first instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.
阐明:返回字符串 chars 中的任一个字符在字符串 s 中第一次呈现的地位
如果找不到,则返回 -1,如果 chars 为空,则返回 -1
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
s := "hello h golang 世界! GO GO GO"
fmt.Println(strings.IndexAny(s, "bbc"))
fmt.Println(strings.IndexAny(s, "elly")) // e 这个字符呈现在了第 1 个索引地位
fmt.Println(strings.IndexAny(s, "dof")) // d 没有呈现在字符中,o 呈现在第 4 个索引地位,也就是说 dof 按字符程序顺次查看
}
//output
//-1
//1
//4
LastIndex
func LastIndex(s, substr string) int
阐明:返回字符串 substr 在 s 中最初一次呈现的地位
如果找不到,则返回 -1,如果 sep 为空,则返回字符串的长度
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
s := "hello h golang 世界! GO GO GO"
fmt.Println(strings.LastIndex(s, "o")) // 从前面输入的构造看,查找辨别大小写
fmt.Println(strings.LastIndex(s, "G")) // 从前面输入的构造看,查找辨别大小写
fmt.Println(strings.LastIndex(s, "go"))
}
//output:
//9
//29
//8
IndexRune
func IndexRune(s string, r rune) int
IndexRune returns the index of the first instance of the Unicode code point r, or -1 if rune is not present in s. If r is utf8.RuneError, it returns the first instance of any invalid UTF-8 byte sequence.
阐明:返回字符串 r 在字符串 s 中第一次呈现的地位
如果找不到,则返回 -1
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
s := "hello h golang 世界! GO GO GO"
fmt.Println(strings.IndexRune(s, '\n'))
fmt.Println(strings.IndexRune(s, '界'))
fmt.Println(strings.IndexRune(s, 0))
}
//output:
//-1
//18
//-1
2、是否蕴含
Contains
func Contains(s, substr string) bool
Contains reports whether substr is within s.
阐明:s 是否蕴含 substr 字符串,返回 true 或 false
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
a := "hello"
b := "el"
c := "world"
fmt.Println(strings.Contains(a, b))
fmt.Println(strings.Contains(a, c))
}
//output:
//true
//false
ContainsAny
func ContainsAny(s, chars string) bool
ContainsAny reports whether any Unicode code points in chars are within s.
阐明:在 s 中是否蕴含 chars 中任一字符,如果是 返回 true,不是 返回 false
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
a = "hello"
b = "e & o"
c = "ebe"
fmt.Println(strings.ContainsAny(a, b))
fmt.Println(strings.ContainsAny(a, c)) //e, b, e 是否在 "hello" 中
}
//output:
//true
//true
ContainsRune
func ContainsRune(s string, r rune) bool
阐明:判断字符串 s 中是否蕴含字符 r
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
a := "hello"
b := "el"
c := "world"
fmt.Println(strings.Contains(a, b))
fmt.Println(strings.Contains(a, c))
a = "hello"
b = "e & o"
c = "ebe"
fmt.Println(strings.ContainsAny(a, b))
fmt.Println(strings.ContainsAny(a, c))
fmt.Println("======contains rune=======")
s := "Hello, 世界!"
fmt.Println(strings.ContainsRune(s, 2)) // false
fmt.Println(strings.ContainsRune(s, rune('e'))) // true
fmt.Println(strings.ContainsRune(s, 'e')) // true
fmt.Println(strings.ContainsRune(s, '界')) //true
}
//output:
//false
//true
//true
//true
3、查找前缀后缀
HasPrefix
func HasPrefix(s, prefix string) bool
阐明:s 的前缀是否蕴含 prefix 字符
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {fmt.Println(strings.HasPrefix("hello", "lo")) //false
fmt.Println(strings.HasPrefix("hello", "O")) //false
fmt.Println(strings.HasPrefix("Hello", "hel")) // false, 辨别大小写
fmt.Println(strings.HasPrefix("Hello", "Hel")) //true
}
//output:
//false
//false
//false
//true
HasSuffix
func HasSuffix(s, suffix string) bool
阐明:跟下面的函数 HasPrefix 相同,s 字符串后缀中是否蕴含 suffix 字符
4、计数
Count
https://godoc.org/strings#Count
func Count(s, substr string) int
Count counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
阐明:如果 substr 存在 s 中,那么返回多少个;如果 substr 为空字符串,那么返回 s 的长度 + 1
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {fmt.Println("========Count========")
s := "Banana"
fmt.Println(strings.Count(s, "ban")) //result:0
fmt.Println(strings.Count(s, "ana")) //result:1
fmt.Println(strings.Count(s, "")) //result:7
}
二:比拟
compare
godoc.org 的 compare
func Compare(a, b string) int
Compare returns an integer comparing two strings lexicographically. The result will be
0 if a==b,
-1 if a < b,
and +1 if a > b.
阐明:a,b 2 个字符串比拟,如果相等,返回 0;如果 a < b,返回 -1;如果 a > b,返回 1;
辨别大小写的比拟
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
a := "hello"
b := "hello"
c := "world"
d := "llo"
e := "Hello"
fmt.Println(strings.Compare(a, b))
fmt.Println(strings.Compare(a, c))
fmt.Println(strings.Compare(a, d))
fmt.Println(strings.Compare(d, a))
fmt.Println(strings.Compare(a, e)) // 后果为 1 不相等,阐明 compare 会辨别大小写
}
//output:
//0
//-1
//-1
//1
//1
EqualFold
func EqualFold(s, t string) bool
EqualFold reports whether s and t, interpreted as UTF-8 strings, are equal under Unicode case-folding.
阐明:UTF- 8 字符串比拟的话,不辨别大小写
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
a := "hello"
e := "Hello"
fmt.Println(strings.EqualFold(a, e))
}
//output:
//true
三:字符变大小写
ToLower
func ToLower(s string) string
阐明:把字符串 s 变成大写
例子 1:
fmt.Println(strings.ToLower("Hello World")) //hello world
ToUpper
func ToUpper(s string) string
阐明:把字符串 s 变大写
例子 1:
fmt.Println(strings.ToUpper("Hello World")) //HELLO WORLD
ToTitle
func ToTitle(s string) string
阐明:把字符串 s 变大写
例子 1:
fmt.Println(strings.ToTitle("He llo")) //HE LLO
Title
https://godoc.org/strings#Title
func Title(s string) string
阐明:把首字母变大写
例子 1:
fmt.Println(strings.Title("hello world")) //Hello World
其余一些函数
用一些规定把字符变成大小写
func ToLowerSpecial(c unicode.SpecialCase, s string) string
func ToUpperSpecial(c unicode.SpecialCase, s string) string
func ToTitleSpecial(c unicode.SpecialCase, s string) string
例子 1:
fmt.Println(strings.ToLowerSpecial(unicode.TurkishCase, "Önnek İş"))
fmt.Println(strings.ToUpperSpecial(unicode.TurkishCase, "örnek iş"))
四:替换过滤
Replace
func Replace(s, old, new string, n int) string
阐明:将字符串 s 中的 old 字符串替换为 new 字符串,n 示意替换次数,如果 n=-1,全副替换;如果 old 为空,则每个字符都插入一个 new 字符
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello World"
fmt.Println(strings.Replace(s, "",",", -1)) //result: Hello,World,
fmt.Println(strings.Replace(s, "",",", 1)) //result: Hello,World
}
Trim
func Trim(s string, cutset string) string
阐明:删除字符串 s 首尾间断蕴含 cutset 的字符
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello World, HDHe"
fmt.Println(strings.Trim(s, "He")) //llo World, HD
}
TrimSpace
func TrimSpace(s string) string
TrimSpace returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.
例子 1:
fmt.Println(strings.TrimSpace("\t\n Hello, Gophers \n\t\r\n")) //Hello, Gophers
TrimPrefix TrimSuffix
func TrimPrefix(s, prefix string) string
func TrimSuffix(s, suffix string) string
阐明:从第一个字符开始,过滤掉右边的字符
过滤掉左边的字符
例子 1:
fmt.Println(strings.TrimPrefix("Hello World, He", "He")) //llo World, He
fmt.Println(strings.TrimPrefix("Hello World, He", "el")) //Hello World, He
fmt.Println(strings.TrimSuffix("Hello World, He", "H")) //Hello World, He
fmt.Println(strings.TrimSuffix("Hello World, He", "He")) //Hello World,
其余一些过滤
func TrimLeft(s string, cutset string) string
func TrimRight(s string, cutset string) string
阐明:从右边开始过滤,cutset 有间断的字符在 s 中,都过滤掉
从左边开始过滤
例子 1:
fmt.Println(strings.TrimLeft("¡¡¡Hello, Gophers!!!", "!¡Ho")) //ello, Gophers!!!
fmt.Println(strings.TrimLeft("¡¡¡Hello, Gophers!!!", "!¡e")) //Hello, Gophers!!!
fmt.Println(strings.TrimLeft("¡¡¡Hello, Gophers!!!", "!el")) //¡¡¡Hello, Gophers!!!
带有解决办法的函数:
func TrimLeftFunc(s string, f func(rune) bool) string
func TrimRightFunc(s string, f func(rune) bool) string
阐明:用函数来解决字符
例子 1:
fmt.Println(strings.TrimLeftFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {return !unicode.IsLetter(r) && !unicode.IsNumber(r)
})) //Hello, Gophers!!!
fmt.Println(strings.TrimRightFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {return !unicode.IsLetter(r) && !unicode.IsNumber(r)
})) //¡¡¡Hello, Gophers
五:宰割和连贯
Split SplitAfter
func Split(s, sep string) []string // 依照 sep 进行宰割
func SplitAfter(s, sep string) []string // 把宰割字符 sep 也带上
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello World, HDHe, gopher!"
fmt.Printf("%q\n", strings.Split(s, ",")) //["Hello World" "HDHe" "gopher!"]
fmt.Printf("%q\n", strings.Split("o Hello World, gopher", "o"))
//output: ["""Hell" "World, gopher"]
fmt.Printf("%q\n", strings.Split("Hello World", ""))
//["H" "e" "l" "l" "o" """W""o" "r" "l" "d"]
}
例子 2:
package main
import (
"fmt"
"strings"
)
func main() {fmt.Printf("%q\n", strings.SplitAfter("Hello, World, Go", ","))
//["Hello," "World," "Go"]
}
SplitN SplitAfterN
func SplitN(s, sep string, n int) []string // 依据分隔符来宰割字符串,n 示意分成多少份
func SplitAfterN(s, sep string, n int) []string // 把分隔符 sep 也带上,n 示意分成多少份
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {fmt.Printf("%q\n", strings.SplitN("Hello, World, Go, He", ",", 2)) //["Hello" "World, Go, He"]
fmt.Printf("%q\n", strings.SplitAfterN("Hello, World, Go, He", ",", 2)) //["Hello," "World, Go, He"]
fmt.Printf("%q\n", strings.SplitAfterN("Hello, World, Go, He", ",", 3)) //["Hello," "World," "Go, He"]
}
Join
func Join(a []string, sep string) string
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {fmt.Println(strings.Join([]string{"hello", "world"}, ",")) //hello, world
}
六:字符读写
Builder
构造体
// A Builder is used to efficiently build a string using Write methods.
// It minimizes memory copying. The zero value is ready to use.
// Do not copy a non-zero Builder.
type Builder struct {
addr *Builder // of receiver, to detect copies by value
buf []byte}
A Builder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use. Do not copy a non-zero Builder.
这个构造能使写字符时候更加高效,应用更小的内存
在 Go 1.10 以前咱们 hi 怎么做的呢?
package main
import (
"bytes"
"fmt"
)
func main() {
// 以前咱们这样来做
fmt.Println("=====bytesbuffer====")
var buf bytes.Buffer
for i, p := range []int{2, 3, 5, 7, 11, 13} {fmt.Fprintf(&buf, "%d:%d,", i+1, p)
}
buf.Truncate(buf.Len() - 2) // Remove trailing ","
s := buf.String() // Copy into a new string
fmt.Println(s)
/**
output:
=====bytesbuffer====
1:2, 2:3, 3:5, 4:7, 5:11, 6:13
**/
}
当初咱们能够用 builder 了
package main
import (
"bytes"
"fmt"
"strings"
)
func main() {fmt.Println("=======Builder=======")
// 当初咱们能够这样做
var b strings.Builder
b.Grow(32)
for i, p := range []int{2, 3, 5, 7, 11, 13} {fmt.Fprintf(&b, "%d:%d,", i+1, p)
}
s := b.String() // no copying
s = s[:b.Len()-2] // no copying (removes trailing ",")
fmt.Println(s)
/**
output:
=======Builder=======
1:2, 2:3, 3:5, 4:7, 5:11, 6:13
**/
}
Reader
构造体
// A Reader implements the io.Reader, io.ReaderAt, io.Seeker, io.WriterTo,
// io.ByteScanner, and io.RuneScanner interfaces by reading
// from a string.
// The zero value for Reader operates like a Reader of an empty string.
type Reader struct {
s string
i int64 // current reading index
prevRune int // index of previous rune; or < 0
}
// Reader 构造通过读取字符串,实现了 io.Reader,io.ReaderAt,// io.Seeker,io.WriterTo,io.ByteScanner,io.RuneScanner 接口
// NewReader returns a new Reader reading from s.
// It is similar to bytes.NewBufferString but more efficient and read-only.
// 通过字符串 s 创立 strings.Reader 对象
// 这个函数相似于 bytes.NewBufferString
// 但比 bytes.NewBufferString 更有效率,而且只读
func NewReader(s string) *Reader {return &Reader{s, 0, -1} }
计算长度 Len
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello, World"
r := strings.NewReader(s)
fmt.Println(r.Len()) //12
}
读取数据
func (r *Reader) Read(b []byte) (n int, err error)
func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)
func (r *Reader) ReadByte() (byte, error)
func (r *Reader) ReadRune() (ch rune, size int, err error)
例子 1:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello, World"
r := strings.NewReader(s)
fmt.Println(r.Len()) //12
b := make([]byte, 5)
for n, _ := r.Read(b); n > 0; n, _ = r.Read(b) {fmt.Printf("%q,", b[:n])
}
//"Hello", ", Wor", "ld",
fmt.Println("======ReadAt========")
r = strings.NewReader(s) // 创立 reader
b = make([]byte, 5) // 创立长度为 5 个字节的缓冲区
n, _ := r.ReadAt(b, 0)
fmt.Printf("%q\n", b[:n]) //"Hello"
n, _ = r.ReadAt(b, 7)
fmt.Printf("%q\n", b[:n]) //"World"
// 读取 r 中的一个字节
for i := 0; i < 3; i++ {b, _ := r.ReadByte()
fmt.Printf("%q,", b) // 'H', 'e', 'l',
}
}
参考:
https://godoc.org/strings
https://yourbasic.org/golang/string-functions-reference-cheat-sheet/
https://www.cnblogs.com/golove/p/3236300.html