Java - word中每个字母的打印数量
Java - print amount of each letter in word
我正在练习算法,我遇到了一个问题,我必须说明单词中每个字母出现了多少。例如输入 = 地板,输出 = 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
,当我输入 floor 作为输入时
您的问题是您打印出了字符的 ascii 码值。尝试
System.out.print(wordArray[i]+"" + count);
而不是
System.out.print(wordArray[i] + count);
考虑到StringUtils.countMatches()
的执行是正确的,问题出在
行
System.out.print(wordArray[i] + count);
在这里,当你做 wordArray[i]
时,它 returns 一个 char
。但是,执行 +count
,将 char
转换为其 ASCII
值,并将 count
添加到它。
要修复它,请尝试执行以下操作:-
System.out.print(wordArray[i] + " " + count);
首先,您应该使用countMatches(word, wordArray[i]);
,但这并不能解决全部问题。例如,您的方法将导致输出 "f1l1o2o2r1",而对于单词 "boohoo",您将得到 "b1o4o4h1o4o4"。
如果您希望输出显示连续相同字母的数量 ("b1o2h1o2"),或者如果您希望每个字母的数量按首次出现的顺序仅指定一次 ("b1o4h1"), 或者字母按字母顺序出现的次数 ("b1h1o4").
我正在练习算法,我遇到了一个问题,我必须说明单词中每个字母出现了多少。例如输入 = 地板,输出 = 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
,当我输入 floor 作为输入时
您的问题是您打印出了字符的 ascii 码值。尝试
System.out.print(wordArray[i]+"" + count);
而不是
System.out.print(wordArray[i] + count);
考虑到StringUtils.countMatches()
的执行是正确的,问题出在
System.out.print(wordArray[i] + count);
在这里,当你做 wordArray[i]
时,它 returns 一个 char
。但是,执行 +count
,将 char
转换为其 ASCII
值,并将 count
添加到它。
要修复它,请尝试执行以下操作:-
System.out.print(wordArray[i] + " " + count);
首先,您应该使用countMatches(word, wordArray[i]);
,但这并不能解决全部问题。例如,您的方法将导致输出 "f1l1o2o2r1",而对于单词 "boohoo",您将得到 "b1o4o4h1o4o4"。
如果您希望输出显示连续相同字母的数量 ("b1o2h1o2"),或者如果您希望每个字母的数量按首次出现的顺序仅指定一次 ("b1o4h1"), 或者字母按字母顺序出现的次数 ("b1h1o4").