1 问题
在编程中,我们会遇到需要统计一段字符中字符的数量的问题,我们该如何解决这些问题呢?
2 方法
我们可以利用ASKII编码再加上for循环和条件判断来进行转换,这样就可以分别计算出数字、字母、及其他字符的数量
package test; import java.util.Scanner; public class Work2 { public static void main(String[] args) { int word = 0; int space= 0; int num = 0; int other = 0; Scanner s = new Scanner(System.in); System.out.println("请输入字符:"); String str = s.nextLine(); char[] arr = new char[str.length()]; for (int i = 0; i < str.length(); i++) { char a = str.charAt(i); if ((int) a >= 65 && (int) a <= 90 || (int) a >= 97 && (int) a <= 122) { word++; } else if ((int) a == 32) { space++; } else if ((int) a >= 48 && (int) a <= 57) { num++; } else { other++; } } System.out.println("英文字母有:" + word + "个"); System.out.println("空格有:" + space + "个"); System.out.println("数字有:" + num + "个"); System.out.println("其他字符:" + other + "个"); } } |
3 结语
针对如何计算字符串数量的问题,提出通过利用ASKII编码和循环判断的方法,通过java的编程实验,证明该方法是有效的,本文只是单纯对字母,数字及空格进行区分,之后还可以更加细节。例如大小写也进行区分。