江海区建设局网站,网站免费制作教程,建设网站的时候,2022年最新热点素材一、题目描述
输入一行字符#xff0c;分别统计出包含英文字母、空格、数字和其它字符的个数。
数据范围#xff1a;输入的字符串长度满足 1 \le n \le 1000 \1≤n≤1000 。
二、输入描述
输入一行字符串#xff0c;可以有空格。
三、输出描述
统计其中英文字符#…一、题目描述
输入一行字符分别统计出包含英文字母、空格、数字和其它字符的个数。
数据范围输入的字符串长度满足 1 \le n \le 1000 \1≤n≤1000 。
二、输入描述
输入一行字符串可以有空格。
三、输出描述
统计其中英文字符空格字符数字字符其他字符的个数。
四、解题思路
读取输入的一行字符串 s初始化变量 letters、spaces、digits 和 others 分别表示英文字母、空格、数字和其他字符的个数初始值都为 0使用循环遍历字符串 s的每个字符 如果字符是英文字母使用 Character.isLetter© 判断将 letters 自增 1如果字符是数字使用 Character.isDigit© 判断将 digits 自增 1如果字符是空格使用 Character.isSpaceChar© 判断将 spaces 自增 1如果字符不是英文字母、数字或空格则将 others 自增 1 循环结束后输出 letters、spaces、digits 和 others 的值分别表示英文字母、空格、数字和其他字符的个数
五、Java算法源码
public static void main(String[] args) {Scanner scanner new Scanner(System.in);while (scanner.hasNext()) {String s scanner.nextLine();//统计其中英文字符空格字符数字字符其他字符的个数int letters 0;int spaces 0;int digits 0;int others 0;int len s.length();for(int i 0; i len; i){char c s.charAt(i);if(Character.isLetter(c)){letters;}else if(Character.isDigit(c)){digits;}else if(Character.isSpaceChar(c)){spaces;}else{others;}}// 统计其中英文字符空格字符数字字符其他字符的个数System.out.println(letters);System.out.println(spaces);System.out.println(digits);System.out.println(others);}
}六、效果展示 下一篇华为OD机试真题 Java 实现【组合出合法最小数】【2023Q1 200分】附详细解题思路
本文收录于华为OD机试2023Java
本专栏包含了最新最全的2023年华为OD机试真题有详细的分析和Java解答。已帮助1000同学顺利通过OD机考。专栏会持续更新每天在线答疑。