题解 | #统计字符#
统计字符
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) }