7-7 统计数字字符和空格*

本题要求编写程序,输入一行字符,统计其中数字字符、空格和其他字符的个数。建议使用switch语句编写。

switch case default: break

输入格式:

输入在一行中给出若干字符,最后一个回车表示输入结束,不算在内。

输出格式:

在一行内按照

blank = 空格个数, digit = 数字字符个数, other = 其他字符个数

的格式输出。请注意,等号的左右各有一个空格,逗号后有一个空格。

输入样例:

在这里给出一组输入。例如:

Reold 12 or 45T

输出样例:

在这里给出相应的输出。例如:

blank = 3, digit = 4, other = 8
# 读取一行输入
input_str = input()

# 初始化空格、数字字符和其他字符的计数器
blank_count = 0
digit_count = 0
other_count = 0

# 遍历输入字符串中的每个字符
for char in input_str:
    if char.isspace():
        blank_count += 1
    elif char.isdigit():
        digit_count += 1
    else:
        other_count += 1

# 按照指定格式输出结果
print(f"blank = {blank_count}, digit = {digit_count}, other = {other_count}")
#include 
int main() {
    char ch;
    int blank = 0, digit = 0, other = 0;
    while ((ch = getchar()) != '\n') {
        switch (ch) {
            case ' ':
                blank++;
                break;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                digit++;
                break;
            default:
                other++;
                break;
        }
    }
    printf("blank = %d, digit = %d, other = %d\n", blank, digit, other);

    return 0;
}

你可能感兴趣的:(算法,python,c,c#)