Go 程序打印字符串字符

编写一个 Go 程序来打印给定字符串中的总字符数。在此示例中,我们打印完整的字符串。

package main

import "fmt"

func main() {

    var strData string

    strData = "Tutorial Gateway"

    fmt.Printf("%s", strData)
    fmt.Println(strData)
}
Tutorial Gateway
Tutorial Gateway

使用 For 循环打印字符串字符的 Go 程序

此 Golang 程序中的 for 循环 (for i := 0; i < len(strData); i++) 从头到尾迭代字符串字符。printf 语句打印索引位置和字符串中的原始字符。

package main

import "fmt"

func main() {

    var strData string

    strData = "Tutorial Gateway"

    for i := 0; i < len(strData); i++ {
        fmt.Printf("Character at %d Index Position = %c\n", i, strData[i])
    }
}
Character at 0 Index Position = T
Character at 1 Index Position = u
Character at 2 Index Position = t
Character at 3 Index Position = o
Character at 4 Index Position = r
Character at 5 Index Position = i
Character at 6 Index Position = a
Character at 7 Index Position = l
Character at 8 Index Position =  
Character at 9 Index Position = G
Character at 10 Index Position = a
Character at 11 Index Position = t
Character at 12 Index Position = e
Character at 13 Index Position = w
Character at 14 Index Position = a
Character at 15 Index Position = y

此 Golang 程序使用 for 循环范围 (for i, c := range strData) 来打印字符串字符及其对应的索引位置。

package main

import "fmt"

func main() {

    strData := "Golang Programs"

    for i, c := range strData {
        fmt.Printf("Character at %d Index Position = %c\n", i, c)
    }
}
Go Program to Print String Characters