SoFunction
Updated on 2025-03-05

Summary of searching strings in Go language

Contains(s, substr string) bool This function is to find out whether a character exists in this string. It returns true if it exists.

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("widuu", "wi")) //true
 (("wi", "widuu")) //false
}


ContainsAny(s, chars string) bool This is to query whether the string contains multiple characters.

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("widuu", "w&d")) //true
}


ContainsRune(s string, r rune) bool, of course, is whether the rune type is included in the string, where the rune type is a type that can fully represent all Unicode characters.

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("widuu", rune('w'))) //true
 (("widuu", 20))        //fasle
}


Count(s, sep string) int is the output, how many matching characters are there in a string

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("widuu", "uu")) //1
 (("widuu", "u"))  //2
}

Index(s, sep string) int This function is to search for a string, then return the current position, and the input is all string type, and then the position information of int

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("widuu", "i")) //1
 (("widuu", "u")) //3
}


IndexAny(s, chars string) int This function is the same search. If the string does not exist, it returns -1.

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("widuu", "u")) //3
}


IndexByte(s string, c byte) int, this function still finds the position of the first thick line, but this time C is of byte type, finds the return position, but cannot find the return -1

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("hello xiaowei", 'x')) //6
}


IndexRune(s string, r rune) int, or search for location, but this time it is of rune type

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("widuu", rune('w'))) //0
}


IndexFunc(s string, f func(rune) bool) int function will be known at a glance. It uses the function to find the location through type conversion. Let's take a look at the code.

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("nihaoma", split)) //3
}

func split(r rune) bool {
 if r == 'a' {
  return true
 }
 return false
}


LastIndex(s, sep string) int When you see this, you may also understand that the search is the last location, which is exactly the opposite of index

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("widuu", "u")) // 4
}


LastIndexAny(s, chars string) int is exactly the opposite of indexAny, and it is also the last one to search for

Copy the codeThe code is as follows:

import (
 "fmt"
 "strings"
)

func main() {
 (("widuu", "u")) // 4
}