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


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

strings.IndexRune() Golang中的函數用於查找給定字符串中指定符文的第一個索引。它是在字符串包下定義的,因此,您必須在程序中導入字符串包才能訪問IndexRune函數

用法:

func IndexRune(str string, r rune) int

此函數返回Unicode代碼點的第一個實例的索引,即指定的符文;如果給定的字符串中不存在指定的符文,則返回-1。如果符文是utf8.RuneError,則它將返回任何無效UTF-8字節序列的第一個實例。

範例1:

// Golang program to show the usage 
// of strings.IndexRune() Function 
package main 
  
// importing fmt and strings 
import ( 
    "fmt"
    "strings"
) 
  
func main() { 
  
    // Returns the index of 'G' in string. 
    fmt.Println(strings.IndexRune("This is GeeksForGeeks", 'G')) 
  
    // Returns -1 because 'y' is not present in string. 
    fmt.Println(strings.IndexRune("This is GeeksForGeeks", 'y')) 
}

輸出:

8
-1

範例2:

// Golang program to show the usage 
// of strings.IndexRune() Function 
package main 
  
// importing fmt and strings 
import ( 
    "fmt"
    "strings"
) 
  
func main() { 
  
    // Returns -1 because of case-sensitive matching. 
    fmt.Println(strings.IndexRune("This is GeeksForGeeks", 'g')) 
  
    // Returns the index of space in string. 
    fmt.Println(strings.IndexRune("This is GeeksForGeeks", ' ')) 
}

輸出:

-1
4



相關用法


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