首頁 >後端開發 >Golang >如何在 Go 中透過 Runes 迭代字串?

如何在 Go 中透過 Runes 迭代字串?

Patricia Arquette
Patricia Arquette原創
2024-11-27 15:34:111113瀏覽

How Do I Iterate Over Strings by Runes in Go?

Go 中透過符文迭代字串

在Go 中,當嘗試使用索引迭代字串時,您可能會遇到以下問題: str[i] 傳回一個位元組而不是符文。這是因為 Go 中的字串是位元組序列,而不是符文。

要按符文迭代字串,請使用 range 關鍵字。例如:

for pos, char := range "日本語" {
    fmt.Printf("character %c starts at byte position %d\n", char, pos)
}

這將列印:

character 日 starts at byte position 0
character 本 starts at byte position 3
character 語 starts at byte position 6

範圍語法執行以下操作:

  • 從0 迭代到字串的長度
  • 對於每個位置,使用UTF-8 提取該位置的符文編碼

以上是如何在 Go 中透過 Runes 迭代字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn