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

Golang determines whether a character exists in a string

Release: 2020-01-09 16:36:21
Original
9424 people have browsed it

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"))
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template