/*
取出一个字符串中字母出现的次数。
如:字符串:"aacdghfsaac",
输出格式为:a(4)c(2)d(1)...
*/
import java.util.Scanner;
class Text1 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串");
String L = sc.nextLine(); //输入一个字符串
String[] str = new String[52]; //这个字符串组用来接收元素,如str[0] = "a(2)"
int[] arr = new int[52]; //用来接收字符出现的个数
int index = 0; //初始索引定义为零
for (int i = 97;i<=122;i++) { //先对a~z的字符进行统计
for (int j = 0;j<L.length();j++) {
if ( L.charAt(j) == (char)i) {
arr[index]++;
}
}
if (arr[index]>0) { //对出现了的字符赋值
str[index] = (char)i+"("+arr[index]+")";
index++; //每赋值一次索引加一
}
}
for (int i = 65;i<=90;i++) { //再对A~Z的字符统计,原理同上
for (int j = 0;j<L.length();j++) {
if ( L.charAt(j) == (char)i) {
arr[index]++;
}
}
if (arr[index]>0) {
str[index] = (char)i+"("+arr[index]+")";
index++;
}
}
for (int i = 0;i<index;i++) { //遍历字符串组,赋值到哪就遍历到哪
System.out.print(str[i]);
}
}
}
|
|