java判断字符个数

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java判断字符个数

小孙的代码分享   2022-05-23 我要评论

描述

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

输入描述:

控制台随机输入一串字符串

输出描述:

输出字符串中包含的英文字母个数,数字个数,空格个数,其它字符个数(格式为:英文字母x数字x空格x其他x),预设代码中已给出输出.

import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        int numbers = 0;
        int words = 0;
        int space = 0;
        int other = 0;
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
 
        //write your code here......
        
 
        System.out.println("英文字母"+words+"数字"+numbers+"空格"+space+"其他"+other);
    }
}
import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        int numbers = 0;
        int words = 0;
        int space = 0;
        int other = 0;
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
 
        //write your code here......
        for(int i=0;i<str.length();i++){
            char c=str.charAt(i);
            if((c>='a' && c<='z')|| (c>='A' && c<='Z')){
                words++;
                continue;
            }
            if(c>='0' && c<='9' ){
                numbers++;
                continue;
            }
            if(c==' '){
                space++;
                continue;
            }
            else{
                other++;
                continue;
            }
        }
 
        System.out.println("英文字母"+words+"数字"+numbers+"空格"+space+"其他"+other);
    }
}
 
 

注意:每次计数完后要跳出循环,否则就取出的字符会挨个问一遍判断语句 出现问题 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们