Home >Backend Development >Golang >Golang determines whether a character exists in a string

Golang determines whether a character exists in a string

尚
Original
2020-01-09 16:36:219427browse

Golang determines whether a character exists in a string

Golang's method of determining whether a character exists in a string:

Determine the position (index) where a substring or character appears in the parent string

Index returns the index of string str in string s (the index of the first character of str) , -1 means that string s does not contain string str:

strings.Index(s, str string) int

LastIndex returns the index of the last occurrence of string str in string s ( The first character of str index), -1 means that the string s does not contain the string str:

strings.LastIndex(s, str string) int

If ch is a non-ASCII encoded character, it is recommended to use the following function Position characters:

strings.IndexRune(s string, ch int) int

Example:

package main
import (
"fmt"
"strings"
)
func main() {
var str string = "Hi, I'm Marc, Hi."
fmt.Printf("The position of \"Marc\" is: ")
fmt.Printf("%d\n", strings.Index(str, "Marc"))
fmt.Printf("The position of the first instance of \"Hi\" is: ")
fmt.Printf("%d\n", strings.Index(str, "Hi"))
fmt.Printf("The position of the last instance of \"Hi\" is: ")
fmt.Printf("%d\n", strings.LastIndex(str, "Hi"))
fmt.Printf("The position of \"Burger\" is: ")
fmt.Printf("%d\n", strings.Index(str, "Burger"))
}

For more golang knowledge, please pay attention to the PHP Chinese websitegolang Tutorial column.

The above is the detailed content of Golang determines whether a character exists in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn