求出字符串中有多少种字符,以及每个字符的个数例如有字符串 str="apple";
结果应该是a:1 p:2 l:1 e:1
求个简单点的方法
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]+"次");
}
}
}
}
从别的问题中找到的,应该可以
while(!"".equals(str)){
String c = str.substring(0,1);
String tempStr = str.replace(c,"");
System.out.println(c+":"+(str.length()-tempStr.length()));
str=tempStr;}