第一种风格的源代码:
package 第四天;
import java.util.Scanner;
public class 统计字符 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a = new int[26];//数组存放对应26个字母的出现次数比如a[0]的值对应字母a出现的次数,a[2]的值对应c出现的次数。。。
System.out.println("请输入一串小写字符串");
String str=sc.nextLine();
str=str.trim().toLowerCase();//去掉前后空格并且全转为小写字母
//此for循环求各个字母出现的次数
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);//依次取出每个字母
int index=c-'a';//这样就可以得到每个字母对应的数组下标
a[index]=a[index]+1;//对应字母出现则存储字母的数组加1
}
//此for循环打印每个字母出现的次数,没有出现则不打印输出
for (int i = 0; i < a.length; i++)
{
if(a[i]!=0)//等于0相当于这个字母没出现就没必要打印
{
System.out.println("字母"+(char)(i+'a')+"出现:"+a[i]+"次");
}
}
}
}
第一种风格的源代码:把统计字母个数包装成了一个静态方法
package 第三天_练习题;
import java.util.Scanner;
public class 统计字符个数 {
// 静态方法统计出每个字母出现的次数
public static int[] countLetters(String str)
{
int[] a = new int[26];
// 此for循环求各个字母出现的次数
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);// 依次取出每个字母
int index = c - 'a';// 这样就可以得到每个字母对应的数组下标
a[index] = a[index] + 1;// 对应字母出现则存储字母的数组加1
}
return a;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int[] a = countLetters(str);//调用统计各字母出现次数的函数,返回类型是数组
//此for循环打印每个字母出现的次数,没有出现则不打印输出
for (int i = 0; i < a.length; i++)
{
if(a[i]!=0)//等于0相当于这个字母没出现就没必要打印
{
System.out.println("字母"+(char)(i+'a')+"出现:"+a[i]+"次");
}
}
}
}
原文:http://blog.csdn.net/u012110719/article/details/42744957