计算字符出现的次数
package baidu;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
import org.junit.experimental.max.MaxCore;
import org.omg.CORBA.PRIVATE_MEMBER;
/**
* 测试用例:1.用字符串2.一个字符3.没有重复的字符串4.有重复的字符串5.全是用一个字符
* public char charAt(int index)--返回指定索引处的 char 值。
* @author 2萌
*
*/
public class StringCount {
/**
* 定义一个新的数组count[],长度为128
* 考虑:为什么要定义一个数组长度为128呢???因为要匹配的字符根据
* ASCII码 是从 0开始的,所以为256个,前128个为常用的字符 如 运算符、字母、数字等键盘上可以显示的;
* 后 128个为 特殊字符 是键盘上找不到的字符。
*/
static int count[] = new int[128];
public static void statisticalLetterNumber(char[] ch) {
if (null == ch) {
System.out.println("字符串为空");
return;
}
//static void fill(int[] a, int val)
// 将指定的 int 值分配给指定 int 型数组的每个元素。
Arrays.fill(count, 0);
for (int i = 0; i < ch.length; i++) {
int index = (int)ch[i];
count[index]++;
}
for (int i = 0; i < 128; i++) {
if (count[i] > 1) {
System.out.print((char) i + "=" + count[i] + " ");
}
}
// max(count);
}
// private static int max(int[] cl) {
// //找出数组里面的最大值
// int max = count[0];
// for (int i = 1; i < count.length; i++) {
// if (max < count[i]) {
// max = count[i];
// }
// }
//
// System.out.println(max);
// return max;
// }
public static void main(String[] args) {
String string = "sssddsddsdsmmm";
// Scanner scanner = new Scanner(System.in);
// String string;
// System.out.println("请输入一个字符串");
// while ((string = scanner.next()) != null) {
//public char[] toCharArray()将此字符串转换为一个新的字符数组。
statisticalLetterNumber(string.toCharArray());
// }
}
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: c语言中函数能返回一个数组吗
- 下一篇: mysql 慢查询日志
