统计字符个数-golang实现 | JianLinker Blog

统计字符个数-golang实现

题目

输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

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

func count(str string) (wordCount, spaceCount, numberCount, otherCount int) {
t := []rune(str)
for _, v := range t {
switch {
case v >= 'a' && v <= 'z':
fallthrough
case v >= 'A' && v <= 'Z':
wordCount++
case v == ' ':
spaceCount++
case v >= '0' && v <= '9':
numberCount++
default:
otherCount++
}
}
return
}

func main() {
reader := bufio.NewReader(os.Stdin)
result, _ , err := reader.ReadLine()
if err != nil {
fmt.Println("read from console err :", err)
}

wc, sc, nc, oc := count(string(result))
fmt.Printf(" wordCount: %d\n spaceCount: %d\n numberCount: %d\n otherCount: %d\n", wc, sc, nc, oc)
}
JianLinker wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!