Golang strings.Index()函数及示例

Golang strings.Index()函数及示例

strings.Index()函数是Go语言中非常常见的字符串处理函数之一。该函数可以用来查找一个字符串在另一个字符串中第一次出现的位置,并返回该位置的索引值。本文将为大家介绍strings.Index()函数的用法,并提供一些示例代码。

函数签名

strings.Index()函数的函数签名如下:

func Index(s, substr string) int

该函数接受两个字符串参数,分别是主字符串s和要查找的子字符串substr,函数返回值为int类型,表示子字符串在主字符串中第一次出现的位置的索引值。如果子字符串不存在于主字符串中,则返回-1

示例代码

示例1:查找子字符串在主字符串中的位置

以下示例展示了如何使用strings.Index()函数查找一个子字符串在主字符串中的位置:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "hello world"
    substr := "world"
    index := strings.Index(str, substr)
    if index == -1 {
        fmt.Printf("'%s' not found in '%s'\n", substr, str)
    } else {
        fmt.Printf("'%s' found in '%s' at position %d\n", substr, str, index)
    }
}

以上代码将输出:

'world' found in 'hello world' at position 6

示例2:检查子字符串是否存在于主字符串中

以下示例展示了如何使用strings.Index()函数检查一个子字符串是否存在于主字符串中:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "hello world"
    substr := "world"
    if strings.Index(str, substr) == -1 {
        fmt.Printf("'%s' not found in '%s'\n", substr, str)
    } else {
        fmt.Printf("'%s' found in '%s'\n", substr, str)
    }
}

以上代码将输出:

'world' found in 'hello world'

示例3:使用Index函数查找子字符串所有出现位置的索引值

以下示例展示了如何使用strings.Index()函数查找一个子字符串在主字符串中的所有出现位置的索引值:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "hello world, hello Gopher, hello everyone"
    substr := "hello"
    for i := strings.Index(str, substr); i != -1; i = strings.Index(str, substr) {
        fmt.Printf("'%s' found at position %d\n", substr, i)
        str = str[i+len(substr):] // 将主字符串缩小为剩余部分
    }
}

以上代码将输出:

'hello' found at position 0
'hello' found at position 12
'hello' found at position 26

结论

strings.Index()函数是Go语言中常用的字符串处理函数之一,它可以用来查找一个字符串在另一个字符串中第一次出现的位置。本文提供了使用该函数的示例代码,希望能帮助读者更好地理解该函数的用法。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程