Java - 单词中每个字母的打印量

时间:2017-03-16 18:28:03

标签: java netbeans command-line netbeans-8

我正在练习算法,我遇到了这个问题,我必须说明单词中每个字母的出现次数。例如input = floor,output = 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);
        }
    }

但是当我输入floor作为输入

时,我将其作为输出:103109113113115

3 个答案:

答案 0 :(得分:1)

您的问题是您打印出char的ascii-code值。尝试

System.out.print(wordArray[i]+"" + count);

而不是

System.out.print(wordArray[i] + count);

答案 1 :(得分:1)

首先,您应该使用countMatches(word, wordArray[i]);但这并不能解决整个问题。例如,你的方法将导致&#34; f1l1o2o2r1&#34;的输出,对于单词&#34; boohoo&#34;,你会得到&#34; b1o4o4h1o4o4&#34;。 如果您希望输出显示连续相同字母的数量(&#34; b1o2h1o2&#34;),或者如果您希望每个字母的编号只按一次指定,则需要重新考虑如何执行此操作外观(&#34; b1o4h1&#34;),或按字母顺序出现的字母数(&#34; b1h1o4&#34;)。

答案 2 :(得分:0)

考虑到StringUtils.countMatches()的实现是正确的,问题在于

System.out.print(wordArray[i] + count);

此处,当您执行wordArray[i]时,它会返回char。但是,执行+count会将char转换为ASCII值,并将count加到其中。

要修复它,请尝试: -

System.out.print(wordArray[i] + " " + count);