Go語言程式:迭代字串中的每個字元


在Go語言中,字串是字元的集合。由於Go語言中的字串是不可變的,因此一旦建立就無法修改。但是,可以透過連線或新增到現有字串來建立新的字串。字串型別是Go語言中的內建型別,可以像其他任何資料型別一樣以多種方式使用。

語法

func len(v Type) int

len() 函式用於獲取任何引數的長度。它接受一個引數作為我們要查詢其長度的資料型別變數,並返回一個整數型別的返回值,表示該變數的長度。

func Split(str, sep string) []string

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

演算法

  • 步驟 1 − 建立一個名為 main 的包並宣告 fmt(格式化包)包

  • 步驟 2 − 建立一個 main 函式,並在該函式中建立一個要迭代其每個字元的字串。

  • 步驟 3 − 使用使用者定義的函式或內部函式來迭代字串的每個字元

  • 步驟 4 − 使用 fmt.Println() 函式執行列印語句,其中 ln 表示換行。

示例 1

在這個例子中,我們將看到如何使用 for 迴圈迭代字串的每個字元。輸出將是列印在控制檯上的字元以及一個空格字元。

package main
import "fmt"

func main() {
	mystr := "Hello, alexa!" //create string
	fmt.Println("The original string given here is:", mystr)
	fmt.Println("The iteration performed through each character of string:")
	for i := 0; i < len(mystr); i++ {   //run a loop and iterate through each character
		fmt.Printf("%c ", mystr[i])  //print characters along with the space character
	}
}

輸出

The original string given here is: Hello, alexa!
The iteration performed through each character of string:
H e l l o ,   a l e x a ! 

示例 2

在這個例子中,我們將看到如何使用 rune() 方法迭代字串的每個字元,其中 str 被轉換為 rune 切片,然後進一步迭代並列印到控制檯。

package main
import "fmt"
func main() {
	mystr := "Hello, alexa!"  //create string
	fmt.Println("The original string given here is:", mystr)
	runes := []rune(mystr)  //turn string to slice 
	fmt.Println("The iteration performed through each character of string:")

	for _, v := range runes { //iterate through rune
		fmt.Printf("%c ", v)  //print characters along with space character
	}
}

輸出

The original string given here is: Hello, alexa!
The iteration performed through each character of string:
H e l l o ,   a l e x a ! 

示例 3

在這個例子中,我們將瞭解如何使用 strings.Split() 函式迭代字串的每個字元,它將字串分割成切片並迭代每個字元。

package main
import (
	"fmt"
	"strings"
)

func main() {
	mystr := "Hello, alexa!"   //create string
	fmt.Println("The original string given here is:", mystr)
	fmt.Println("The iteration performed through each character of string:")
	for _, slice := range strings.Split(mystr, "") {  //use built-in function to split the string
		fmt.Printf("%s ", slice)  //print the characters along with space character
	}
}

輸出

The original string given here is: Hello, alexa!
The iteration performed through each character of string:
H e l l o ,   a l e x a !

結論

我們透過三個示例執行了迭代字串中每個字元的程式。在第一個示例中,我們使用了 for 迴圈;在第二個示例中,我們使用了 rune() 內建函式;在第三個示例中,我們使用了 strings.Split() 函式。

更新於:2023年2月1日

瀏覽量:9K+

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告