Golang 迭代遍历字符串中的每个字符

Golang 迭代遍历字符串中的每个字符

在Golang中,字符串是字符的集合。由于Go中的字符串是不可变的,所以它们在生成后不能被修改。然而,可以通过连接或添加到现有字符串来创建新的字符串。作为Go中的一种内置类型,字符串类型可以像任何其他数据类型一样以各种方式使用。

语法

func len(v Type) int

len()函数用于获取任何参数的长度。它接受一个参数作为数据类型变量,我们希望找到它的长度,并返回整数值,该值是变量的长度。

func Split(str, sep string) []string

split()函数用于通过提供的分隔符拆分字符串。该函数存在于字符串包中,它接受要拆分的字符串作为参数以及一个分隔符。然后,该函数将结果作为最终字符串数组返回。

步骤

  • 步骤1 - 创建主要包并声明fmt(格式包)包

  • 步骤2 - 创建主函数,并在该函数中创建一个字符串,其中每个字符都被迭代。

  • 步骤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被转换为runes的切片,并进一步迭代和打印在控制台上。

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()函数。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程