当前位置:网站首页>Input a line of characters to count the English letters, spaces, numbers and other characters

Input a line of characters to count the English letters, spaces, numbers and other characters

2022-06-25 21:22:00 vancomycin

The knowledge points needed here :

1、 Get a line of string ,nextLine()

2、 Assign each character of the string to a value

3、 Compare each value in ASK Code range , You can determine the category of its symbols

4、char character ASK Code range

(1) Numbers 0 To 9: 48~57

(2) Letter A To Z:65 To 90   a To z:97 To 122

(3) Space is 32

The above knowledge points need to be memorized , Otherwise, the problem can not be solved at all .

thought : The first thing you must think of when doing this problem is how to input all the characters, how to traverse the string, and then add them up , The first thing to do is , Convert this string to char An array of types , Only then can we judge , A single string cannot be judged .

String s1 = "ab2";

char [] c1 = s1.toCharArray();      // This line of code converts the string to char Array of .

Then define several integer values

        int num = 0;          // The number of numbers
        int letter = 0;         // The number of letters     
        int space = 0;        // The number of spaces
        int others = 0;        // Other numbers

After use for Loop traversal and accumulation , utilize    if    also   else   if    The above knowledge points are nested in , Complete pair of numbers , Letter , And spaces , Judgment of other characters . Finally, the information found above is accumulated .

The detailed code is as follows :

package com.qfedu.test;

import java.util.Scanner;

public class Test2 {
	public static void main(String args[]) {
		int num = 0;   //  The number of numbers 
		int letter = 0;		// The number of letters 	
		int space = 0;		// The number of spaces 
		int others = 0;			// Other numbers 
		Scanner input =new Scanner(System.in);
		System.out.println(" Please enter a string of characters , Easy to count the letters , Numbers , Space , And other characters ");
		String str = input.nextLine();
		char arr[] = str.toCharArray();
		for (int i = 0; i < arr.length; i++) {
			if (arr[i]>=48&&arr[i]<=57) {  // Characters are numbers 
				num++;
			}else if ((arr[i]>=65&&arr[i]<=90)||(arr[i]>=97&&arr[i]<=122)) {
				letter++;
			}else if (arr[i]==32) {
				space++;
			}else {
				others++;
			}
		}
		System.out.println(" Numbers :"+num+" individual ,  Letter :"+letter+" Space :"+space+" individual ,  other "+others);
		
	}
}

原网站

版权声明
本文为[vancomycin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202181329516120.html