我正在练习算法,我遇到了这个问题,我必须说明单词中每个字母中出现了多少个。 例如,输入 = 地板 , 输出 = F1L1O2R1。我有以下代码:
public static void main(String[] args) {// TODO code application logic here
Scanner inword = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("Enter word");
String word = inword.nextLine();
int length = word.length();
char[] wordArray = word.toCharArray();
for(int i = 0; i<length; i++){
int count = StringUtils.countMatches(word, String.valueOf(wordArray[i]));
System.out.print(wordArray[i] + count);
}
}
但相反,我得到这个作为输出:103109113113115
,当我输入地板时
您的问题是打印出字符的 ascii 代码值。
System.out.print(wordArray[i]+"" + count);
而不是
System.out.print(wordArray[i] + count);
首先,你应该使用countMatches(word, wordArray[i]);
但这并不能解决整个问题。例如,您的方法将导致输出"f1l1o2o2r1",对于单词"boohoo",您将获得"b1o4o4o4h1o4o4"。如果您希望输出显示连续相同字母的数量("b1o2h1o2"(,或者如果您希望每个字母的数量仅指定一次,按首次出现的顺序("b1o4h1"(或字母的出现次数("b1h1o4"(,您需要重新考虑如何做到这一点。
考虑到StringUtils.countMatches()
的实现是正确的,问题出在行
System.out.print(wordArray[i] + count);
在这里,当你执行wordArray[i]
时,它会返回一个char
。但是,执行+count
,会将该char
转换为其ASCII
值,并将count
加起来。
要修复它,请尝试执行以下操作:-
System.out.print(wordArray[i] + " " + count);