import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CountChar {
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args) {
String str = "yu#$SdwssddddDDDddasasas";
countChar(str);
System.out.println("#####################################");
countCharMap(str);
System.out.println("#####################################");
countChar(str, str.length());
}
/**
* 使用char判断来统计
*/
public static void countChar(String str) {
String noRepet = "";
str = str.toLowerCase();
int num = 0;
Character ch = null;
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (noRepet.equals("")) {
noRepet += ch;
} else if (noRepet.indexOf(ch) == -1) {
noRepet += ch;
} else {
continue;
}
for (int j = 0; j < str.length(); j++) {
if (str.charAt(j) == ch) {
num++;
}
}
System.out.println(ch + " : " + num);
num = 0;
}
}
/**
* 使用哈希表来统计
*/
public static void countCharMap(String str) {
char[] k = str.toLowerCase().toCharArray();
Map<Character, Integer> res = new HashMap<Character, Integer>(k.length);
List<Character> l = new ArrayList<Character>(k.length);
for (char c : k) {
if (res.containsKey(c)) {
res.put(c, res.get(c) + 1);
} else {
l.add(c);
res.put(c, 1);
}
}
for (Character c : l) {
System.out.println("" + c + " : " + res.get(c));
}
}
/**
* 使用字节来统计
*/
public static void countChar(String input, int len) {
int counts[] = new int[255];
char orders[] = new char[255];
int nextChPos = 0;
for (int i = 0; i < len; i++) {
char lowerCase = Character.toLowerCase(input.charAt(i));
// do not need track more than once
if (counts[lowerCase & 0xff]++ == 0) {
orders[nextChPos] = lowerCase;
nextChPos = lowerCase & 0xff;
}
}
for (char c = orders[0]; c > 0;) {
System.out.println(c + " : " + counts[(c & 0xff)]);
c = orders[c];
}
}
}
统计字符串出现的次数
最新推荐文章于 2023-07-11 15:51:29 发布