扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
Golang中strings如何使用,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
创新互联公司是少有的成都网站建设、网站设计、营销型企业网站、微信小程序定制开发、手机APP,开发、制作、设计、外链、推广优化一站式服务网络公司,自2013年起,坚持透明化,价格低,无套路经营理念。让网页惊喜每一位访客多年来深受用户好评
一:查找
godoc.org上索引的方法
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
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
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
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
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
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
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
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
func HasSuffix(s, suffix string) bool
说明:跟上面的函数 HasPrefix 相反, s 字符串后缀中是否包含 suffix 字符
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 }
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
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
func ToLower(s string) string
说明:把字符串 s 变成大写
例子1:
fmt.Println(strings.ToLower("Hello World")) //hello world
func ToUpper(s string) string
说明:把字符串 s 变大写
例子1:
fmt.Println(strings.ToUpper("Hello World")) //HELLO WORLD
func ToTitle(s string) string
说明:把字符串 s 变大写
例子1:
fmt.Println(strings.ToTitle("He llo")) //HE LLO
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ş"))
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 }
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 }
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
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
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"] }
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"] }
func Join(a []string, sep string) string
例子1:
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Join([]string{"hello", "world"}, ", ")) //hello, world }
结构体
// 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 **/ }
结构体
// 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', } }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流