Java 程序用于查找字符串中大写字母、小写字母、数字和特殊字符的百分比
本文将教会我们如何将字符串转换为字符数组,以便检查其组成。接下来,我们将对每个字符进行分类,将其归类为数字、特殊字符、小写字母或大写字母。我们将使用Java Character 类的方法来实现这一点。对于每个组(大写、小写、数字和特殊字符),我们将计算百分比并显示结果。
isUpperCase() :Java Character 的 isUpperCase() 方法用于确定字符是否为大写字符。
isLowerCase() :Java Character 的 isLowerCase() 方法用于确定字符是否为小写字符。
isDigit() :Java Character 的 isDigit() 方法用于检查指定字符是否为数字。
问题陈述
将给定的字符串转换为字符数组,并使用 Character 类的 isUpperCase()、isLowerCase()、isDigit() 方法验证数组中每个字符是大写、小写、数字还是其他字符。
输入
Hello HOW are you MR 51
输出
Total length of the string :23
Upper case :6
Percentage of upper case letters: 26
Lower case :10
Percentage of lower case letters:43
Digit :2
Percentage of digits :8
Others :5
Percentage of other characters :21
查找百分比的步骤
以下是查找字符串中大写字母、小写字母、数字和特殊字符百分比的方法:
- 初始化一个类
- 在主方法中定义一个字符串并将其转换为字符数组。
- 为大写字母、小写字母、数字和特殊字符创建计数器。
- 使用length() 方法获取字符串的长度。
- 使用for 循环遍历数组,使用Character.isUpperCase()、Character.isLowerCase()和Character.isDigit() 方法更新计数器。
- 计算每种字符类型的百分比。
- 显示每种字符类型的总长度、计数和百分比。
Java 程序用于查找百分比
以下是 Java 程序,用于查找字符串中大写字母、小写字母、数字和特殊字符的百分比:
public class Sample2 {
public static void main(String args[]) {
String data = "Hello HOW are you MR 51";
char [] charArray = data.toCharArray();
int upper = 0;
int lower = 0;
int digit = 0;
int others = 0;
int totalChars = data.length();
for(int i=0; i<data.length(); i++) {
if (Character.isUpperCase(charArray[i])) {
upper++;
} else if(Character.isLowerCase(charArray[i])) {
lower++;
} else if(Character.isDigit(charArray[i])){
digit++;
} else {
others++;
}
}
System.out.println("Total length of the string :"+totalChars);
System.out.println("Upper case :"+upper);
System.out.println("Percentage of upper case letters: "+(upper*100)/totalChars);
System.out.println("Lower case :"+lower);
System.out.println("Percentage of lower case letters:"+(lower*100)/totalChars);
System.out.println("Digit :"+digit);
System.out.println("Percentage of digits :"+(digit*100)/totalChars);
System.out.println("Others :"+others);
System.out.println("Percentage of other characters :"+(others*100)/totalChars);
}
}
输出
Total length of the string :23 Upper case :6 Percentage of upper case letters: 26 Lower case :10 Percentage of lower case letters:43 Digit :2 Percentage of digits :8 Others :5 Percentage of other characters :21
代码解释
在上面给出的程序中,我们首先将在提供的 Java 程序中定义 Sample2 类。我们将使用data.toCharArray(),在主方法内部将字符串数据转换为字符数组。然后初始化大写、小写、数字和其他字符的计数器。我们使用Character.isUpperCase()、Character.isLowerCase()和Character.isDigit()通过 for 循环检查每个字符的类型。根据结果,我们增加相应的计数器。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP