Golang中strings如何使用

Golang中strings如何使用,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

創(chuàng)新互聯(lián)公司是少有的成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、營銷型企業(yè)網(wǎng)站、微信小程序定制開發(fā)、手機(jī)APP,開發(fā)、制作、設(shè)計(jì)、外鏈、推廣優(yōu)化一站式服務(wù)網(wǎng)絡(luò)公司,自2013年起,堅(jiān)持透明化,價格低,無套路經(jīng)營理念。讓網(wǎng)頁驚喜每一位訪客多年來深受用戶好評

一:查找

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中第一次出現(xiàn)的位置

  • 如果找不到則返回-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 中第一次出現(xiàn)的位置

  • 如果找不到,則返回 -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這個字符出現(xiàn)在了第1個索引位置
	fmt.Println(strings.IndexAny(s, "dof")) //d沒有出現(xiàn)在字符中,o出現(xiàn)在第4個索引位置,也就是說dof按字符順序依次檢查
}
//output
//-1   
//1
//4

LastIndex

func LastIndex(s, substr string) int

說明:

  • 返回字符串substr在s中最后一次出現(xiàn)的位置

  • 如果找不到,則返回 -1,如果 sep 為空,則返回字符串的長度

例子1:

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "hello h golang 世界! GO GO GO"

	fmt.Println(strings.LastIndex(s, "o")) //從后面輸出的結(jié)構(gòu)看,查找區(qū)分大小寫
	fmt.Println(strings.LastIndex(s, "G")) //從后面輸出的結(jié)構(gòu)看,查找區(qū)分大小寫
	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 中第一次出現(xiàn)的位置

  • 如果找不到,則返回 -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, 區(qū)分大小寫
	fmt.Println(strings.HasPrefix("Hello", "Hel")) //true
}
//output:
//false
//false
//false
//true

HasSuffix

func HasSuffix(s, suffix string) bool

說明:跟上面的函數(shù) HasPrefix 相反, s 字符串后綴中是否包含 suffix 字符

4、計(jì)數(shù)

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;

  • 區(qū)分大小寫的比較

例子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)) //結(jié)果為1 不相等,說明compare會區(qū)分大小寫
}

//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字符串比較的話,不區(qū)分大小寫

例子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

其他一些函數(shù)

用一些規(guī)則把字符變成大小寫

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 表示替換次數(shù), 如果 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 首尾連續(xù)包含 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有連續(xù)的字符在 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!!!

帶有處理方法的函數(shù):

func TrimLeftFunc(s string, f func(rune) bool) string

func TrimRightFunc(s string, f func(rune) bool) string

說明:用函數(shù)來處理字符

例子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 進(jìn)行分割

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         //根據(jù)分隔符來分割字符串,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

結(jié)構(gòu)體

// 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.

這個結(jié)構(gòu)能使寫字符時候更加高效,使用更小的內(nèi)存

在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
	  **/
}

現(xiàn)在我們可以用builder了

package main

import (
	"bytes"
	"fmt"
	"strings"
)

func main() {
	fmt.Println("=======Builder=======")
	//現(xiàn)在我們可以這樣做
	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

結(jié)構(gòu)體

// 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 結(jié)構(gòu)通過讀取字符串,實(shí)現(xiàn)了 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 創(chuàng)建 strings.Reader 對象
// 這個函數(shù)類似于 bytes.NewBufferString
// 但比 bytes.NewBufferString 更有效率,而且只讀
func NewReader(s string) *Reader { return &Reader{s, 0, -1} }

計(jì)算長度 Len

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Hello, World"
	r := strings.NewReader(s)

	fmt.Println(r.Len()) //12
}

讀取數(shù)據(jù)

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) //創(chuàng)建reader
	b = make([]byte, 5)      //創(chuàng)建長度為 5 個字節(jié)的緩沖區(qū)
	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 中的一個字節(jié)
	for i := 0; i < 3; i++ {
		b, _ := r.ReadByte()
		fmt.Printf("%q, ", b) // 'H', 'e', 'l',
	}

}

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。

文章題目:Golang中strings如何使用
文章路徑:http://muchs.cn/article4/gphooe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、網(wǎng)站建設(shè)關(guān)鍵詞優(yōu)化、網(wǎng)頁設(shè)計(jì)公司移動網(wǎng)站建設(shè)、ChatGPT

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護(hù)公司