题解 | #统计字符#

统计字符

https://www.nowcoder.com/practice/539054b4c33b4776bc350155f7abd8f5

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	input := scanner.Text()

	var (
		letterCount int
		spaceCount  int
		numberCount int
		otherCount  int
	)
	for i := 0; i < len(input); i++ {
		ch := input[i]
		switch {
		case ch >= 'A' && ch <= 'Z', ch >= 'a' && ch <= 'z':
			letterCount++
		case ch >= '0' && ch <= '9':
			numberCount++
		case ch == ' ':
			spaceCount++
		default:
			otherCount++
		}
	}
	fmt.Println(letterCount)
	fmt.Println(spaceCount)
	fmt.Println(numberCount)
	fmt.Println(otherCount)

}

错误代码:

package main

import ( "fmt" "unicode" )

func main() { var str string fmt.Scanln(&str)

letterCount := 0
spaceCount := 0
numberCount := 0
otherCount := 0

for _, ch := range str {
    if unicode.IsLetter(ch) {
        letterCount++
    } else if unicode.IsSpace(ch) {
        spaceCount++
    } else if unicode.IsNumber(ch) {
        numberCount++
    } else {
        otherCount++
    }
}

fmt.Printf("英文字母个数:%d\n", letterCount)
fmt.Printf("空格个数:%d\n", spaceCount)
fmt.Printf("数字个数:%d\n", numberCount)
fmt.Printf("其他字符个数:%d\n", otherCount)
}

全部评论

相关推荐

07-02 18:09
门头沟学院 Java
苍穹外卖和谷粒商城这俩是不是烂大街了,还能做吗?
想去重庆的鸽子在吐槽:你不如把这俩做完自己搞明白再优化点再来问 何必贩卖焦虑
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务