Java程序来计算字符串中每个字符的频率
时间:2020-01-09 10:35:25 来源:igfitidea点击:
在本文中,我们将看到一个Java程序来计算字符串中每个字符的频率。这里给出了两种计算每个字符在字符串中出现的次数的方法。
- 使用HashMap,其中character是键,count是值。对于每个字符,我们都需要验证密钥是否已存在于HashMap中。如果是的话,请增加计数,否则将其作为新密钥添加到地图中,计数为1. 请参见示例。
- 另一种方法是使用char数组,我们将必须在数组的第一个索引处获取char并迭代整个数组以检查是否再次找到该char,如果是,则增加计数。最后,使用String类的replace()方法删除该字符的所有出现。参见示例。
Java程序使用HashMap计数每个字符的频率
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class CountChars {
public static void main(String[] args) {
CountChars.countCharactersMap("This is a test line");
}
public static void countCharactersMap(String str){
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
for(int i = 0; i < str.length(); i++){
char c = str.charAt(i);
// For space or tab skip the process
if(((c == ' ') || (c == '\t'))){
continue;
}
// if character is already there in the map
// increment the count
if(charMap.containsKey(c)){
charMap.put(c, charMap.get(c) + 1);
}else{
// If new character put that character in the map
// with the value as 1
charMap.put(c, 1);
}
}
// Displaying the map values
Set<Map.Entry<Character, Integer>> numSet = charMap.entrySet();
for(Map.Entry<Character, Integer> m : numSet){
System.out.println(m.getKey() + " - " + m.getValue());
}
}
}
输出
a - 1 s - 3 T - 1 t - 2 e - 2 h - 1 i - 3 l - 1 n - 1
使用char数组和String replace()方法
这是一个Java程序,用于使用char数组和String replace()方法对String中每个字符的频率进行计数。
public class CountChars {
public static void main(String[] args) {
CountChars.countCharacters("This is a test line");
}
public static void countCharacters(String str){
char[] strArr;
do{
strArr = str.toCharArray();
char ch = strArr[0];
int count = 1;
for(int i = 1; i < strArr.length; i++){
if(ch == strArr[i]){
count++;
}
}
// don't display for space or tab
if(((ch != ' ') && (ch != '\t'))){
System.out.println(ch + " - " + count);
}
// replace all occurrence of the character
// which is already counted
str = str.replace(""+ch, "");
// If string is of length 0 then come
// out of the loop
if(str.length() == 0) {
break;
}
}while(strArr.length > 1);
}
}
输出
T - 1 h - 1 i - 3 s - 3 a - 1 t - 2 e - 2 l - 1 n - 1

