Go語言程式:使用索引從字串中獲取字元


在 Go 語言中,有多種方法可以使用索引從字串中獲取字元。本文將介紹使用外部函式和 Go 語言內建函式的方法。

方法 1:使用使用者自定義函式

在這種方法中,我們建立的函式將接收需要確定其字元的字串以及字串的整數型別索引作為引數,並返回該索引處字串的字元。

演算法

  • 步驟 1 − 首先,我們需要匯入 fmt 包。

  • 步驟 2 − 然後,建立一個函式,該函式將接收需要確定其字元的字串以及索引作為引數。

  • 步驟 3 − 開始 main() 函式。

  • 步驟 4 − 在 main() 函式內部,初始化一個字串型別的變數併為其賦值。

  • 步驟 5 − 在螢幕上列印該變數。

  • 步驟 6 − 初始化一個 int 型別的變數併為其賦值索引值。

  • 步驟 7 − 現在,透過將字元和索引作為引數傳遞給函式,呼叫 getChar() 函式。

  • 步驟 8 − 將函式獲得的結果儲存在字串格式的變數中。

  • 步驟 9 − 使用 fmt.Println() 函式在螢幕上列印此值。

示例

在本示例中,我們將使用使用者自定義的外部函式從字串中獲取字元。

package main
import "fmt"

// function to get characters from strings using index
func getChar(str string, index int) rune {
	return []rune(str)[index]
}
func main() {
   // initializing a string
   var str string = "Prevention is better than cure"
   fmt.Println("The given string is:", str)
   var index int = 24
   var result string = string(getChar(str, index))
   fmt.Println("The character at index", index, "is:", result)
}

輸出

The given string is: Prevention is better than cure
The character at index 24 is: n

方法 2:使用 Split() 函式

我們將使用內建函式獲取字串中存在的字元陣列,然後使用索引獲取該索引處存在的字元值。

語法

func Split(str, sep string) []string

Split() 函式用於透過提供的分隔符分割字串。此函式位於 strings 包中,它接收要分割的字串以及分隔符作為引數。然後,該函式返回最終的字串陣列作為結果。

func Index(s, substr string) int

index() 函式位於 strings 包中,用於獲取給定子字串的第一次出現的索引。該函式接收兩個值作為引數。一個是字串,另一個是要檢測其出現的子字串。然後,該函式以整數格式返回該子字串的第一次出現位置。

演算法

  • 步驟 1 − 首先,我們需要匯入 fmt 和 strings 包。

  • 步驟 2 − 然後,開始 main() 函式。在 main() 函式內部,初始化一個字串型別的變數併為其賦值。

  • 步驟 3 − 此外,在螢幕上列印字串,並分配一個 int 型別的變數並存儲要獲取字元的整數數值。

  • 步驟 4 − 現在,使用 strings 包中的 split() 函式獲取給定字串的字元陣列。

  • 步驟 5 − 現在,使用上面初始化的索引從字元陣列中獲取該值處的字元,並將該字元儲存在單獨的變數中。

  • 步驟 6 − 我們現在已經獲得了我們想要獲取的字元。使用 fmt.Println() 函式在螢幕上列印該字元。

示例 1

在本示例中,我們將使用 strings 包中的 split() 函式將字串轉換為字元。

package main
import (
	"fmt"
	"strings"
)
func main() {
   // initializing a string
   var str string = "Prevention is better than cure"
   fmt.Println("The given string is:", str)
   var index int = 7
   chars := strings.Split(str, "")
   var result string = chars[index]
   fmt.Println("The character at index", index, "is:", result)
}

輸出

The given string is: Prevention is better than cure
The character at index 7 is: i

示例 2

package main
import (
	"fmt"
	"strings"
)
func main() {
   // initializing a string
   var str string = "Prevention is better than cure"
   fmt.Println("The given string is:", str)
   var index int = 17

   var result string = string(str[strings.Index(str, string(str[index]))])
   fmt.Println("The character at index", index, "is:", result)
}

輸出

The given string is: Prevention is better than cure
The character at index 17 is: t

結論

我們已經成功編譯並執行了一個 Go 語言程式,該程式使用索引從字串中獲取字元,並附帶示例。這裡我們編譯了三個示例,第一個示例使用外部函式來實現結果,而第二個和第三個示例使用 Go 語言中存在的庫函式來實現相同的功能。

更新於: 2023年2月13日

4K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告