如何统计一个字符串中的大写字母个数和小写字母个数以及其他字母
(2016-11-15 17:05:25)
标签:
字符串大写字母小写字母统计string |
分类: JAVA |
这里有java的3种思路求解:(注意:当使用其中一种方法时把其他两种进行注释,否则多此一举了!)
public static void
main(String[] args)
{
String s = "SFSAFSDF&*%&sdfsfsdf";
int minNum = 0, maxNum = 0, otherNum = 0;
//分别记录大写字母,小写字母和其他字符的个数
//统计其中大写字母的个数和小写字母的个数和不是字母的个数
//第一种
for(int i = 0; i < s.length(); i++)
{
char a =
s.charAt(i);
if(a >=
'a' && a <= 'z')
{
minNum++;
}
else if(a
>= 'A' && a <= 'Z')
{
maxNum++;
}
else
otherNum++;
}
//第二种
String sL = "abcdefghijklmnopqrstuvwxyz";
String sU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//列出所有的大写字母和小写字母,看看目标字符串中的每个字符是属于大写数组还是小写数组
for(int i = 0; i < s.length(); i++)
{
char a =
s.charAt(i);
if(sL.indexOf(a) != -1)
{
minNum++;
}
else
if(sU.indexOf(a) != -1)
{
maxNum++;
}
else
otherNum++;
}
//第三种
//通过把字符串中的每一个字符提取出来,然后调用字符的判断大写小写方法进行处理
for(int i = 0; i < s.length(); i++)
{
char a =
s.charAt(i);
if(Character.isLowerCase(a))
{
minNum++;
}
else
if(Character.isUpperCase(a))
{
maxNum++;
}
else
otherNum++;
}
System.out.println("大写字母的个数为: " + maxNum);
System.out.println("小写字母的个数为: " + minNum);
System.out.println("不是字母的个数为: " +
otherNum);
}
public class TestString
{
}