您的位置:首页 > 其它

统计字符串中字母,数字,空格以及其他字符的个数。

2017-12-09 20:51 573 查看
题目描述

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

输入

一行字符

输出

统计值

样例输入

aklsjflj123 sadf918u324 asdf91u32oasdf/.';123


样例输出

23 16 2 4

C语言写法

#include <stdio.h>
int main(){    int letters = 0;    int spaces = 0;    int nums = 0;    int others = 0;    char ch;    while ((ch = getchar ()) != '\n')    {        if ((ch>='a' && ch <= 'z') || (ch>='A'&&ch<='Z'))            letters++;        else if (ch>='0' && ch <='9')            nums++;        else if (ch == ' ')            spaces++;        else            others++;    }    printf ("%d %d %d %d\n", letters,nums,spaces,others);    return 0;}Java写法import java.util.Scanner;public class Main{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int count_letters = 0; int count_nums = 0; int count_spaces = 0; int count_others = 0; for(int i = 0;i < s.length();i++) { if((s.charAt(i)>='a'&&s.charAt(i)<='z')||(s.charAt(i)>='A'&&s.charAt(i)<='Z')) { count_letters++; } else if(s.charAt(i) >= '0' && s.charAt(i) <= '9')//注意这个地方也有加上单引号,此处将数字当作字符处理。 { count_nums++; } else if(s.charAt(i) == ' ') { count_spaces++; } else { count_others++; }     } System.out.print(count_letters+" "+count_nums+" "+count_spaces+" "+count_others); }}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐