Go 程序打印字符串字符的 ASCII 值

编写一个 Go 程序来打印字符串所有字符的 ASCII 值。 for 循环(for i := 0; i < len(strData); i++)会迭代字符串的字符,从开头到字符串长度。在循环内,printf 语句会打印 ASCII 值。为此,我们使用 %d 或 %v 字符串格式化选项。

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {

    reader := bufio.NewReader(os.Stdin)

    fmt.Print("Enter Any String to find ASCII Values = ")
    strData, _ := reader.ReadString('\n')

    for i := 0; i < len(strData); i++ {
        fmt.Printf("The ASCII Value of %c = %d\n", strData[i], strData[i])
    }
}
Enter Any String to find ASCII Values = hello
The ASCII Value of h = 104
The ASCII Value of e = 101
The ASCII Value of l = 108
The ASCII Value of l = 108
The ASCII Value of o = 111

Go 程序使用 for 循环 range 打印字符串字符的 ASCII 值

package main

import "fmt"

func main() {

    var strData string

    strData = "Golang Programs"

    for _, c := range strData {
        fmt.Printf("The ASCII Value of %c = %d\n", c, c)
    }
}
Go Program to Print ASCII Value of String Characters

这个 Golang 程序返回字符串字符的 ASCII 值,与第一个示例相同。但是,我们使用了 %v 而不是 %d。

package main

import (
    "fmt"
)

func main() {

    strData := "Tutorial Gateway"

    for i := 0; i < len(strData); i++ {
        fmt.Printf("The ASCII Value of %c = %v\n", strData[i], strData[i])
    }
}
The ASCII Value of T = 84
The ASCII Value of u = 117
The ASCII Value of t = 116
The ASCII Value of o = 111
The ASCII Value of r = 114
The ASCII Value of i = 105
The ASCII Value of a = 97
The ASCII Value of l = 108
The ASCII Value of   = 32
The ASCII Value of G = 71
The ASCII Value of a = 97
The ASCII Value of t = 116
The ASCII Value of e = 101
The ASCII Value of w = 119
The ASCII Value of a = 97
The ASCII Value of y = 121