首页 > 试题广场 >

统计字符

[编程题]统计字符
  • 热度指数:153113 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

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

数据范围:输入的字符串长度满足


输入描述:

输入一行字符串,可以有空格



输出描述:

统计其中英文字符,空格字符,数字字符,其他字符的个数

示例1

输入

1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\\/;p0-=\\][

输出

26
3
10
12
import java.util.*;
import javax.lang.model.util.ElementScanner6;
public class Main{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            char[] ch=sc.nextLine().toCharArray();
            int count1=0;
            int count2=0;
            int count3=0;
            for (int i = 0; i < ch.length; i++) {
                if((ch[i]>='A' && ch[i]<='Z') || (ch[i]>='a' && ch[i]<='z'))
                    count1++;
                else if(ch[i]==' ')
                    count2++;
                else if(ch[i]>='0' && ch[i]<='9')
                    count3++;
            }
            System.out.println(count1);
            System.out.println(count2);
            System.out.println(count3);
            System.out.println(ch.length-count1-count2-count3);
        }
        sc.close();
    }
}
发表于 2018-04-06 18:04:37 回复(2)
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNext()){
			String line = scanner.nextLine();
			System.out.println(getEnglishCharCount(line));
			System.out.println(getBlankCharCount(line));
			System.out.println(getNumberCharCount(line));
			System.out.println(getOtherCharCount(line));
		}
		scanner.close();
	}
	  public static int getEnglishCharCount(String str) {
		  char[] ch = str.toCharArray();
		  int count =0;
		  for(int i=0;i<ch.length;i++){
			  if((ch[i]>='a'&&ch[i]<='z')||(ch[i]>='A'&&ch[i]<='Z')){
				  count++;
			  }
		  }
	        return count;
	  }
	  
	  public static int getNumberCharCount(String str){
		  char[] ch = str.toCharArray();
		  int count =0;
		  for(int i=0;i<ch.length;i++){
			  if(ch[i]>='0'&&ch[i]<='9'){
				  count++;
			  }
		  }
	        return count;
	    }
	  
	  public static int getBlankCharCount(String str){
		  char[] ch = str.toCharArray();
		  int count =0;
		  for(int i=0;i<ch.length;i++){
			  if(ch[i]==' '){
				  count++;
			  }
		  }
	        return count;
	    }
	  
	    public static int getOtherCharCount(String str) {
			 int count =0;
			 for(int i=0;i<str.length();i++){
				 if(getBlankCharCount(""+str.charAt(i))==0&&getEnglishCharCount(""+str.charAt(i))==0&&getNumberCharCount(""+str.charAt(i))==0){
					 count++;
					 
				 }
			 }
	        return count;
	    }
}

发表于 2016-08-09 22:35:28 回复(11)
不懂此题考察什么
#include<iostream>
#include<string>
using namespace std;

int main(){
    string s;
    while(getline(cin,s)){
        int EnglishCharCount =0;
        int BlankCharCount = 0;
        int NumberCharCount = 0;
        int OtherCharCount =0;
        
        
        int length = s.size();
        for(int i =0;i<length;++i){
            char cur = (char)s[i];
            if((cur >= 'a' && cur <='z') || (cur>= 'A' && cur<= 'Z'))
                ++EnglishCharCount;
            else if(cur == ' ')
                ++BlankCharCount;
            else if((cur>='0' && cur<='9'))
                ++NumberCharCount;
            else 
                ++OtherCharCount;
        }
        
        cout<<EnglishCharCount<<endl<<BlankCharCount<<endl<<NumberCharCount<<endl<<OtherCharCount<<endl;
    }
    
    return 0;

发表于 2016-07-13 22:14:20 回复(5)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()) {
            int[] ret = new int[4];
            String s = scan.nextLine();
            char[] input = s.toCharArray();
            for(char c:input) {
                if(Character.isLetter(c)) {
                    ret[0]++;
                }else if(Character.isWhitespace(c)) {
                    ret[1]++;
                }else if(Character.isDigit(c)) {
                    ret[2]++;
                }else {
                    ret[3]++;
                }
            }
            for(int n:ret) {
                System.out.println(n);
            }
        }
    }
}

发表于 2021-01-01 12:34:30 回复(1)
#include<iostream>
using namespace std;
int main(){
    string str;
    while(getline(cin, str)){
		int a[4] = {0};
        for(int i = 0; i < str.size(); ++i){
            if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
                a[0] ++;
            else if(str[i] == ' ')
                a[1] ++;
            else if(str[i] >= '0' && str[i] <= '9')
                a[2] ++;
            else 
                a[3] ++;
        }
        for(int i = 0; i < 4; ++i)
            cout << a[i] << endl;
    }
    return 0;
}

发表于 2017-03-30 21:00:20 回复(2)
/*
水木清华
2020-03-21
/输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。
*/
#include <iostream>
using namespace std;
/*
函数接口1:统计出英文字母字符的个数。
@param str 需要输入的字符串
@return 英文字母字符的个数
*/
int getEnglishCharCount(string str)
{
    int count = 0; //计数器,记录英文字符的个数
    for (int i = 0; i < str.size(); i++)
    {
        if (((str[i] >= 'A') && (str[i] <= 'Z')) || ((str[i] >= 'a') && (str[i] <= 'z')))
        {
            count++;
        }
    }
    return count;
}
/*
函数接口2:统计出空格字符的个数。
@param str 需要输入的字符串
@return 空格字符的个数
*/
int getBlankCharCount(string str)
{
    int count = 0; //计数器,记录空格字符的个数
    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] == ' ')
        {
            count++;
        }
    }
    return count;
}
/*
函数接口3:统计出数字字符的个数。
@param str 需要输入的字符串
@return 数字字符的个数
*/
int getNumberCharCount(string str)
{
    int count = 0; //计数器,记录数字字符的个数
    for (int i = 0; i < str.size(); i++)
    {
        if ((str[i] >= '0') && (str[i] <= '9'))
        {
            count++;
        }
    }
    return count;
}
/*
函数接口4:统计出其它字符的个数。
@param str 需要输入的字符串
@return 其他字符的个数
*/
int getOtherCharCount(string str)
{
    //ASCII 码:最小边界值 0;空格:32;数字:48~57;英文字母:大写 65~90,小写 97~122;最大边界值 127。故对应写出五个区间即可判断其他字符
    int count = 0; //计数器,记录其他字符的个数
    for (int i = 0; i < str.size(); i++)
    {
        if (((str[i] >= 0) && (str[i] < ' ')) || ((str[i] > ' ') && (str[i] < '0')) || ((str[i] > '9') && (str[i] < 'A')) || 
            ((str[i] > 'Z') && (str[i] < 'a')) || ((str[i] > 'z') && (str[i] <= 127)))
        {
            count++;
        }
    }
    return count;
}
//主函数
int main()
{
    string str;
    while (getline(cin, str))
    {
        cout << getEnglishCharCount(str) << '\n' << getBlankCharCount(str) << '\n' 
            << getNumberCharCount(str) << '\n' << getOtherCharCount(str) << endl;
    }
    return 0;
}

发表于 2020-03-21 12:41:03 回复(0)
while True:
    try:

        string = input().strip()
        rst = {'letter': 0, 'digit': 0, 'space': 0, 'othter_char': 0}
        for i in list(string):
            if i == ' ': # 先判断是否为空格,因为ord(' ')空格会报错。
                rst['space'] += 1
            elif ord('A') <= ord(i) <= ord('Z') or ord('a') <= ord(i) <= ord('z'):
                rst['letter'] += 1
            elif ord('0') <= ord(i) <= ord('9'):
                rst['digit'] += 1
            else:
                rst['othter_char'] += 1

        for i in ['letter', 'space', 'digit', 'othter_char']:
            print(rst[i])
    except:
        break
借助ascii码来对比:先判断是否为空格,然后判断是否为字母,然后判断是否为数字,然后剩余的归类为其他字符,将结果存放到一个字典中。遍历这个字典并打印。
编辑于 2019-11-17 23:11:15 回复(0)
 import java.util.*;

public class Main {
	
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {  
        	char[] cs = sc.nextLine().toCharArray();
        	int num1 = 0; // 英文字符个数
        	int num2 = 0; // 空格字符个数
        	int num3 = 0; // 数字字符个数
        	int num4 = 0; // 其它字符个数
        	for(int i = 0; i < cs.length; i++){
        		if((cs[i] >= 'a' && cs[i] <= 'z') || (cs[i] >= 'A' && cs[i] <= 'Z'))
        			num1++;
        		else if(cs[i] == ' ')
        			num2++;
        		else if(cs[i] >= '0' && cs[i] <= '9')
        			num3++;
        		else 
					num4++;			
        	}
        	System.out.println(num1);
        	System.out.println(num2);
        	System.out.println(num3);
        	System.out.println(num4);
        }
        sc.close();
    }
}
发表于 2016-08-14 16:06:01 回复(0)
s = input()
hashtable = {'alpha': 0, ' ':0, 'dig':0, 'other':0}
for i in s:
    if i.isdigit():
        hashtable['dig'] += 1
    elif i.isalpha():
        hashtable['alpha'] += 1
    elif i == ' ':
        hashtable[' '] += 1
    else:
        hashtable['other'] +=1
for i in hashtable.values():
    print(i)

发表于 2022-07-25 19:14:12 回复(0)
请问还有比我的更加简单的java代码没有?
直接输出就行了,【利用正则表达式regex】【优雅,高效】
import java.util.Scanner;
public class Main{   
 public static void main(String[] args) {
       String s = new Scanner(System.in).nextLine();
        //利用正则表达式,替换replaceAll(删除)别的。剩下的就是要求的长度
        System.out.println(s.replaceAll("[^a-zA-Z]","").length());
        System.out.println(s.replaceAll("\\S","").length());
        System.out.println(s.replaceAll("\\D","").length());
        System.out.println(s.replaceAll("[\\s\\da-zA-Z]","").length());
    }
}


发表于 2022-07-05 20:07:06 回复(1)
s=input()
yingwen=0
shuzi=0
kongge=0
qita=0
for i in s:
    if i.isalpha():
        yingwen=yingwen+1
    elif i.isdigit():
        shuzi=shuzi+1
    elif i.isspace():
        kongge=kongge+1
    else:
        qita=qita+1
print(yingwen)
print(kongge)
print(shuzi)
print(qita)

发表于 2022-06-07 12:43:47 回复(1)
用正则表达式
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        countChar(scanner.nextLine());
    }
    public static ArrayList<Integer> countChar(String s){
        ArrayList<Integer> integers = new ArrayList<>(4);//英文字符,空格字符,数字字符,其他字符
        String s1 = s.replaceAll("[a-zA-Z]+", "");//英文字符
        integers.add(s.length()-s1.length());

        String s2 = s1.replace(" ", ""); //空格字符
        integers.add(s1.length()-s2.length());

        String s3 = s2.replaceAll("\\d+", ""); //数字字符
        integers.add(s2.length()-s3.length());

        integers.add(s3.length());//其他字符

        for (Integer integer : integers) {
            System.out.println(integer);
        }
        return null;
    }
}


发表于 2022-05-26 14:58:29 回复(0)
感觉貌似要用到点集合的知识23333
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String inp = sc.nextLine();
        String inp1 = inp.replaceAll("[a-z]+|[A-Z]+", "");
        String inp2 = inp.replaceAll("[0-9]+", "");
        String inp3 = inp.replaceAll(" ", "");
        
        System.out.println(inp.length()-inp1.length());
        System.out.println(inp.length()-inp3.length());
        System.out.println(inp.length()-inp2.length());
        System.out.println(inp1.length()+inp2.length()+inp3.length()-2*inp.length());
    }
}


发表于 2022-04-21 10:39:58 回复(0)
直接调用Character
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int[] newStr = calculate(str);
        System.out.println(newStr[0] + "\n" + newStr[1] + "\n" + newStr[2]
            + "\n" + newStr[3]);
    }
    
    public static int[] calculate(String oldStr) {
        char[] chars = oldStr.toCharArray();
        int len = chars.length;
        int[] times = new int[4];
        for (int i = 0; i < len; i++) {
            if (Character.isLetter(chars[i])) {
                times[0] +=  1;
            } else if (Character.isWhitespace(chars[i])) {
                times[1] +=  1;
            } else if (Character.isDigit(chars[i])) {
                times[2] +=  1;
            } else {
                times[3] +=  1;
            }
        }
        return times;
    }
}


发表于 2022-04-14 10:05:47 回复(0)
#include<stdio.h>
#include<string.h>
int main() {
    char str[1001] = {'\0'};
    while (gets(str)) {
        int len = strlen(str);
        int charac = 0, blank = 0, num = 0, other = 0;
        for (int i = len - 1; i >= 0; i--) {
            //字母计数(区分大小写)
            if ((('a' <= str[i])&&(str[i] <= 'z')) || (('A' <= str[i])&&(str[i] <= 'Z'))) charac++;
            else if (str[i] == ' ') blank++;  //空格计数
            else if (('0' <= str[i]) && (str[i] <= '9')) num++;  //数字计数
            else other++;  //其他字符计数
        }
        printf("%d\n%d\n%d\n%d\n", charac, blank, num, other);
    }
}

发表于 2022-03-31 05:16:47 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int a=0;
            int b=0;
            int c=0;
            int d=0;
            char[]cs=in.nextLine().toCharArray();
            for(char ch:cs){
                if(Character.isDigit(ch)){
                    c++;
                }else if(Character.isLetter(ch)){
                    a++;
                }else if(ch==' '){
                    b++;
                }else d++;
            }
            System.out.println(a);
            System.out.println(b);
            System.out.println(c);
            System.out.println(d);
        }
    }
}
发表于 2022-01-10 17:16:08 回复(2)
while True:
    try:
        line = list(input().strip())
        a, b, c, d = 0,0,0,0
        for i in line:
            if i.isalpha():#检测字符串是否只由字母组成
                a += 1
            elif i.isspace():#检测字符串是否只由空格组成
                b += 1
            elif i.isdigit():#检测字符串是否只由数字组成
                c += 1
            else:
                d += 1
        print(a)
        print(b)
        print(c)
        print(d)
    except EOFError:
        break
发表于 2022-01-10 12:01:40 回复(0)
用正则表达式快速解答
import re
while True:
    try:
        s=input()
        print(len(re.findall('[a-zA-Z]', s)))
        print(len(re.findall(' ', s)))
        print(len(re.findall('[0-9]', s)))
        print(len(re.findall('[^a-zA-Z0-9 ]', s)))
    except:
        break

发表于 2021-11-29 18:30:18 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            int a = 0;
            int b = 0;
            int c = 0;
            for(int i =0;i<str.length();i++){
                char ch = str.charAt(i);
                 if('A' <= ch && ch <='Z' ||'a' <= ch && ch <='z' ){
                         a+=1;
                }else if(ch>='0' && ch<='9'){
                     b+=1;
                 }else if(ch == ' '){
                     c+=1;
                 }
            }
        System.out.println(a);
        System.out.println(c);
         System.out.println(b);
        System.out.println(str.length()-a-b-c);

        }
        
    }
}

发表于 2021-11-07 21:00:55 回复(0)
import java.util.Scanner;

/**
 * @author Yuliang.Lee
 * @version 1.0
 * @date 2021/9/18 10:03
 * 统计字符:
    输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。

  输入:
    1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\\/;p0-=\\][
  输出:
    26
    3
    10
    12
 */
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String input = in.nextLine();
            int letterNum = 0;
            int blankNum = 0;
            int digitNum = 0;
            int otherNum = 0;
            for (int i = 0; i < input.length(); i++) {
                char ch = input.charAt(i);
                if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
                    letterNum++;
                } else if (ch == ' ') {
                    blankNum++;
                } else if (ch >= '0' && ch <= '9') {
                    digitNum++;
                } else {
                    otherNum++;
                }
            }
            System.out.println(letterNum);
            System.out.println(blankNum);
            System.out.println(digitNum);
            System.out.println(otherNum);
        }
    }
}

发表于 2021-09-18 10:27:47 回复(0)