Golang中strings如何使用,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
一:查找
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
//-1func 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
//4func 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
//8func 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
//-1func 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
//falsefunc 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
//truefunc 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
//truefunc 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
//truefunc 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
//1func 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:
//truefunc ToLower(s string) string
說明:把字符串 s 變成大寫
例子1:
fmt.Println(strings.ToLower("Hello World")) //hello worldfunc ToUpper(s string) string
說明:把字符串 s 變大寫
例子1:
fmt.Println(strings.ToUpper("Hello World")) //HELLO WORLDfunc ToTitle(s string) string
說明:把字符串 s 變大寫
例子1:
fmt.Println(strings.ToTitle("He llo")) //HE LLOhttps://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, Gophersfunc 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, Gophersfunc 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',
}
}看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。