方法:首先使用for語(yǔ)句遍歷字符串,語(yǔ)法“for i := 0; i < len(字符串變量); i++{}”或“for _, s := range 字符串變量{}”;然后在循環(huán)體“{}”里使用“fmt.Printf()”函數(shù)逐一輸出即可。
本教程操作環(huán)境:windows10系統(tǒng)、GO 1.11.2、Dell G3電腦。
Go語(yǔ)言遍歷字符串——獲取每一個(gè)字符串元素
遍歷每一個(gè)ASCII字符
遍歷 ASCII 字符使用 for 的數(shù)值循環(huán)進(jìn)行遍歷,直接取每個(gè)字符串的下標(biāo)獲取 ASCII 字符,如下面的例子所示。
package main import "fmt" func main() { theme := "hello php中文網(wǎng)" for i := 0; i < len(theme); i++ { fmt.Printf("ascii: %c %dn", theme[i], theme[i]) } }
程序輸出如下:
ascii: h 104 ascii: e 101 ascii: l 108 ascii: l 108 ascii: o 111 ascii: 32 ascii: p 112 ascii: h 104 ascii: p 112 ascii: ? 228 ascii: ? 184 ascii: - 173 ascii: ? 230 ascii: ? 150 ascii: ? 135 ascii: ? 231 ascii: ? 189 ascii: ? 145
這種模式下取到的漢字“慘不忍睹”。由于沒(méi)有使用 Unicode,漢字被顯示為亂碼。
按Unicode字符遍歷字符串
同樣的內(nèi)容:
package main import "fmt" func main() { theme := "hello php中文網(wǎng)" for _, s := range theme { fmt.Printf("Unicode: %c %dn", s, s) } }
程序輸出如下:
Unicode: h 104 Unicode: e 101 Unicode: l 108 Unicode: l 108 Unicode: o 111 Unicode: 32 Unicode: p 112 Unicode: h 104 Unicode: p 112 Unicode: 中 20013 Unicode: 文 25991 Unicode: 網(wǎng) 32593
可以看到,這次漢字可以正常輸出了。
總結(jié)
-
ASCII 字符串遍歷直接使用下標(biāo)。
-
Unicode 字符串遍歷用 for range。
推薦學(xué)習(xí):Golang教程