我有以下程序可以计算字符串中字符的出现次数。例如,给定一个字符串 - my name is stack overflow
,我希望输出为
f 1 e 2 c 1 a 2 n 1 o 2 l 1 m 2 k 1 i 1 w 1 v 1 t 1 s 2 r 1 y 1
但是,似乎出了点问题,我无法弄清楚是什么。另外,请注意 - 我确实看到了过去发布的一些程序。可能重复。但我想帮助解决我的具体问题,而不是使用其他人的解决方案。
这是代码:
//Count the occurence of a character in a string
package strings;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CharacterOccurenceInAString {
private static Map<Integer, Character> str = new HashMap<Integer, Character>();
private static List<Character> charList = new ArrayList<Character>();
private static Character value;
public static void main(String[] args) {
BufferedReader br = null;
String input = "";
try {
br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter a string");
input = br.readLine();
charOccurence(input);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void charOccurence(String s) {
for (int i = 0; i < s.length(); i++) {
// Don't include white spaces -
if (Character.isWhitespace(s.charAt(i))) {
continue;
} else {
str.put(i, s.charAt(i));
charList.add(s.charAt(i));
}
}
for(Character val:str.values()){
getCount(val);
}
}
static boolean flag = false;
public static int getCount(Character c) {
int ct = 0;
for (int i = 0; i < charList.size(); i++) {
c = charList.get(i);
if (charList.contains(c)) {
ct++;
flag=false;
}
}
if(flag==false)
{
System.out.println(c + ":" + ct);
}
return ct;
}
}
这是我得到的输出:
Please enter a string
my name is stack overflow
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21
w:21