编写一个 Go 程序来判断字符是否为数字。unicode.IsDigit 检查 Rune 是否为数字。我们使用了 If else 语句(if unicode.IsDigit(r))以及 unicode IsDigit 函数来判断给定的字符是否为数字。
package main
import (
"bufio"
"fmt"
"os"
"unicode"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Any Character to Check Digit = ")
r, _, _ := reader.ReadRune()
if unicode.IsDigit(r) {
fmt.Printf("%c is a Digit\n", r)
} else {
fmt.Printf("%c is Not a Digit\n", r)
}
}

Unicode 包还有一个 IsNumber 函数(if unicode.IsNumber(r))来检查字符是否为数字。在这里,我们使用了这个函数。
package main
import (
"bufio"
"fmt"
"os"
"unicode"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Any Character to Check Digit = ")
r, _, _ := reader.ReadRune()
if unicode.IsNumber(r) {
fmt.Printf("%c is a Digit\n", r)
} else {
fmt.Printf("%c is Not a Digit\n", r)
}
}
SureshMac:GoExamples suresh$ go run charIsDigit1.go
Enter Any Character to Check Digit = 8
8 is a Digit
SureshMac:GoExamples suresh$ go run charIsDigit1.go
Enter Any Character to Check Digit = @
@ is Not a Digit
Go 程序判断字符是否为数字
在这个 Go 示例中,我们将给定的字节字符转换为 Rune(if unicode.IsDigit(rune(ch))),然后使用 IsDigit 函数。
package main
import (
"bufio"
"fmt"
"os"
"unicode"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Any Character to Check Digit = ")
ch, _ := reader.ReadByte()
if unicode.IsDigit(rune(ch)) {
fmt.Printf("%c is a Digit\n", ch)
} else {
fmt.Printf("%c is Not a Digit\n", ch)
}
}
SureshMac:GoExamples suresh$ go run charIsDigit2.go
Enter Any Character to Check Digit = 0
0 is a Digit
SureshMac:GoExamples suresh$ go run charIsDigit2.go
Enter Any Character to Check Digit = p
p is Not a Digit
0 到 9 之间的任何数字都称为数字。我们使用 If 条件(if ch >= ‘0’ && ch <= ‘9’)来检查字符是否为数字。
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Any Character to Check Digit = ")
ch, _ := reader.ReadByte()
if ch >= '0' && ch <= '9' {
fmt.Printf("%c is a Digit\n", ch)
} else {
fmt.Printf("%c is Not a Digit\n", ch)
}
}
SureshMac:GoExamples suresh$ go run charIsDigit3.go
Enter Any Character to Check Digit = 2
2 is a Digit
SureshMac:GoExamples suresh$ go run charIsDigit3.go
Enter Any Character to Check Digit = 8
8 is a Digit
此 Golang 程序使用 ASCII 码(if ch >= 48 && ch <= 57)来检查字符是否为数字。
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Any Character to Check Digit = ")
ch, _ := reader.ReadByte()
if ch >= 48 && ch <= 57 {
fmt.Printf("%c is a Digit\n", ch)
} else {
fmt.Printf("%c is Not a Digit\n", ch)
}
}
SureshMac:GoExamples suresh$ go run charIsDigit4.go
Enter Any Character to Check Digit = 5
5 is a Digit
SureshMac:GoExamples suresh$ go run charIsDigit4.go
Enter Any Character to Check Digit = n
n is Not a Digit