Two ways to count the occurrence of uppercase and lowercase letters and numbers in a string

Basic idea: traverse the string through a for loop, return the character at the specified index through the charAt (int index) method in the String class, and then determine whether the upper and lower case letters or numbers are counted through two methods, and finally output the result

method one:

String s = "hjsdg639NJDHjkfh6439hbdJKSHEFLhjsdg";
int upper = 0;
int lower = 0;
int num = 0;
for(int i=0;i<s.length();i++) {
	char c = s.charAt(i);
	if(c>='A' && c<='Z') {
		upper++;
	}
	if(c>='a' && c<='z') {
		lower++;
	}
	if(c>='0' && c<='9') {
		num++;
	}
}
System.out.println("大写字母出现次数为"+upper+"次,小写字母出现次数为"+lower+"次,数字出现次数为"+num+"次");

Method Two:

String s = "hjsdg639NJDHjkfh6439hbdJKSHEFLhjsdg";
int upper = 0;
int lower = 0;
int num = 0;
for(int i=0;i<s.length();i++) {
	char c = s.charAt(i);
	if(Character.isUpperCase(c)) {
		upper++;
	}
	if(Character.isLowerCase(c)) {
		lower++;
	}
	if(Character.isDigit(c)) {
		num++;
	}
}
System.out.println("大写字母出现次数为"+upper+"次,小写字母出现次数为"+lower+"次,数字出现次数为"+num+"次");

 

Published 4 original articles · received 1 · views 187

Guess you like

Origin blog.csdn.net/joeychiang/article/details/104874966