當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang strings.IndexAny()用法及代碼示例

strings.IndexAny() Golang中的函數用於從原始字符串中的chars返回任何Unicode代碼點的第一個實例的索引。如果來自chars的Unicode代碼點在原始字符串中不可用,則此方法將返回-1。

用法:

func IndexAny(str, charstr string) int

在這裏,str是原始字符串,charstr是chars的Unicode代碼點,我們想要查找索引值。

範例1:

// Golang program to illustrate 
// the strings.IndexAny() Function 
package main  
  
import (  
    "fmt"
    "strings"
)  
  
// Main function  
func main() {  
  
    // Creating and initializing the strings  
    str1:= "GeeksforGeeks - A Computer Science Portal"
    str2:= "GFG is the Best"
  
    // Displaying strings  
    fmt.Println("String 1:", str1)  
    fmt.Println("String 2:", str2)  
      
      
    // Finding the index value  
    // of the given strings  
    // Using IndexAny() function  
    res1:= strings.IndexAny(str1, "G")  
    res2:= strings.IndexAny(str2, "Be")  
    res3:= strings.IndexAny("GFG, geeks", "uywq")  
  
    // Displaying the result  
    fmt.Println("\nIndex values:")  
    fmt.Println("Result 1:", res1)  
    fmt.Println("Result 2:", res2)  
    fmt.Println("Result 3:", res3)  
  
} 

輸出:

String 1: GeeksforGeeks - A Computer Science Portal
String 2: GFG is the Best

Index values:
Result 1: 0
Result 2: 9
Result 3: -1

範例2:

// Golang program to illustrate 
// the strings.IndexAny() Function 
package main  
  
import (  
    "fmt"
    "strings"
)  
  
// Main function  
func main() {  
  
    // using the function 
    fmt.Println(strings.IndexAny("Why GFG?", "F"))  
      
} 

輸出:

5



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 strings.IndexAny() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。