Golang strings.Index()函数及示例

Golang strings.Index()函数及示例

strings.Index()函数 在Golang中用于获取特定子字符串的第一个实例。如果未找到子字符串,则该方法将返回-1。

语法:

func Index(str, sbstr string) int

这里,str是原始字符串,sbstr是我们要查找索引值的字符串。

例1:

//演示strings.Index()函数的Go程序
  
package main 
     
import ( 
    "fmt"
    "strings"
) 
     
//主函数 
func main() { 
     
    //创建并初始化字符串 
    str1 := "Welcome to GeeksforGeeks"
    str2 := "My name is XYZ"
     
    //显示字符串
    fmt.Println("字符串1:", str1) 
    fmt.Println("字符串2:", str2) 
     
    //使用Index()函数 
    res1 := strings.Index(str1, "Geeks") 
    res2 := strings.Index(str2, "is") 
   
    //显示结果 
    fmt.Println("\n索引值:") 
    fmt.Println("结果1:", res1) 
    fmt.Println("结果2:", res2) 
     
} ```  

输出:

字符串1: Welcome to GeeksforGeeks
字符串2: My name is XYZ

索引值:
结果1: 11
结果2: 8

例2:

//演示strings.Index()函数的Go程序
  
package main
  
import (
    "fmt"
    "strings"
)
  
//主函数
func main() {
  
    //使用Index()函数
    res1 := strings.Index("GFG", "H")
    res2 := strings.Index("GeeksforGeeks", "for")
  
    //显示结果
    fmt.Println("结果1:", res1)
    fmt.Println("结果2:", res2)
  
} 

输出:

结果1: -1
结果2: 5

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程