Home >Backend Development >Golang >Use the strings.Index function to return the first occurrence of a specified substring in a string
Use the strings.Index function to return the first occurrence position of the specified substring in the string
Introduction:
In the Go language, string manipulation is one of the requirements we often encounter. The strings.Index function is very commonly used in the Go language. It can help us quickly find the first occurrence of a specified substring in a string. This article will introduce how to use the strings.Index function and attach code examples to help readers better understand and apply this function.
1. Introduction to strings.Index function
The strings.Index function is a built-in function in the Go language, used to return the first occurrence position of a specified substring in a string. Its function signature is as follows:
func Index(s, substr string) int
where s is the string to be searched and substr is the substring to be found. This function returns the index value of the first occurrence of substring substr in s, or -1 if it is not found.
2. Usage Example
The following code example demonstrates how to use the strings.Index function to find the first occurrence of a specified substring in a string.
The sample code is as follows:
package main
import (
"fmt" "strings"
)
func main() {
str := "Hello World" substr := "Wo" index := strings.Index(str, substr) if index != -1 { fmt.Printf("子串 "%s" 首次出现的位置是:%d
" , substr, index)
} else { fmt.Printf("子串 "%s" 在字符串中未找到
", substr)
}
}
Code analysis:
Running results:
The first occurrence of the substring "Wo" is: 6
In the above example, the string we need to find is "Hello World", The substring to be found is "Wo". By calling the strings.Index function, the substring "Wo" is found in the string, and its first occurrence is 6.
3. Summary
This article introduces the basic usage of the strings.Index function in the Go language, and shows through code examples how to use this function to return the first occurrence position of a specified substring in a string. I hope readers can better understand and apply the strings.Index function through the instructions and sample code in this article. When encountering similar needs in actual development, you can flexibly use this function to improve development efficiency.
The above is the detailed content of Use the strings.Index function to return the first occurrence of a specified substring in a string. For more information, please follow other related articles on the PHP Chinese website!