计算字符串中出现的字符数

时间:2012-05-25 05:57:11

标签: java string exception string-parsing

我正在尝试编写一个Java程序,它接受一个字符串作为输入,并计算一个字符串中出现的字符数,然后打印一个新字符串,该字符串后跟出现的次数。

E.G。

输入字符串:

aaaabb

输出字符串:

a4b2

输入字符串:

aaaaabbbc

输出字符串:

a5b3c1

我发布了我的java代码 它正在抛出StringOutOfBoundException

/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/

import java.util.Scanner;

public class CountingOccurences {

public static void main(String[] args) {

    Scanner inp= new Scanner(System.in);
    String str;
    char ch;
    int count=0;

    System.out.println("Enter the string:");
    str=inp.nextLine();

    while(str.length()>0)
    {
        ch=str.charAt(0);
        int i=0;

        while(str.charAt(i)==ch)
        {
                count =count+i;
                i++;
        }

        str.substring(count);
        System.out.println(ch);
        System.out.println(count);
    }

}

}

7 个答案:

答案 0 :(得分:3)

这是问题所在:

while(str.charAt(i)==ch)

这将一直持续到它结束......当i与字符串的长度相同时,它将要求超出字符串末尾的字符。你可能想要:

while (i < str.length() && str.charAt(i) == ch)

您还需要在较大循环的每次迭代开始时将count设置为0 - 毕竟计数重置 - 并更改

count = count + i;

要么:

count++;

...或摆脱counti。毕竟,他们总是会有相同的价值。就个人而言,我只使用一个变量,在循环中声明并初始化 。事实上,这是一个通用的样式点 - 在需要时声明局部变量更为清晰,而不是在方法的顶部声明它们。

然而,那么你的程序将永远循环,因为这没有做任何有用的事情:

str.substring(count);

字符串在Java中是不可变的 - substring返回 new 字符串。我想你想要:

str = str.substring(count);

请注意,这仍然会为“aabbaa”输出“a2b2a2”。那可以吗?

答案 1 :(得分:2)

我不想透露完整的代码。所以我想给你挑战,玩得开心。我鼓励你使代码更简单,只有一个循环。

基本上,我的想法是将字符比较并排配对。例如,将char 1与char 2进行比较,将char 2与char 3进行比较,依此类推。当char N与char(N + 1)不同时,则重置字符计数。你只能在一个循环中完成这个!处理这个时,形成一个新的字符串。不要使用与输入相同的字符串。这令人困惑。

请记住,简单易事。开发人员的生活很难看到复杂的代码。

玩得开心!

汤米“我应该当老师”Kwee

答案 2 :(得分:2)

public class StringTest{
public static void main(String[] args){

    String s ="aaabbbbccccccdd";
    String result="";
    StringBuilder sb = new StringBuilder(s);


    while(sb.length() != 0){
        int count = 0;
        char test = sb.charAt(0);
        while(sb.indexOf(test+"") != -1){
            sb.deleteCharAt(sb.indexOf(test+""));
            count++;
        }
        //System.out.println(test+" is repeated "+count+" number of times");
        result=result+test+count;
    }
    System.out.println(result);         
}
}

答案 3 :(得分:0)

如果这是一个真正的程序而不是研究项目,那么请查看使用Apache Commons StringUtils类 - 尤其是countMatches方法。

如果它是一个研究项目,那么请继续学习并从您的探索中学习:)

答案 4 :(得分:-1)

您应该能够使用StringUtils类和countMatches()方法。

  

public static int countMatches(String str,                                  String sub)

Counts how many times the substring appears in the larger String.

尝试以下方法:

int count = StringUtils.countMatches("a.b.c.d", ".");

答案 5 :(得分:-1)

我认为你在寻找的是:

公共课Ques2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String input = br.readLine().toLowerCase();
    StringBuilder result = new StringBuilder();
    char currentCharacter;
    int count;

    for (int i = 0; i < input.length(); i++) {
        currentCharacter = input.charAt(i);
        count = 1;
        while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
            count++;
            i++;
        }
        result.append(currentCharacter);
        result.append(count);
    }

    System.out.println("" + result);
}

}

答案 6 :(得分:-2)

试试这个:

import java.util.Scanner;

    /* Logic: Consider first character in the string and start counting occurrence of        
              this character in the entire string. Now add this character to a empty
              string "temp" to keep track of the already counted characters.
              Next start counting from next character and start counting the character        
              only if it is not present in the "temp" string( which means only if it is
              not counted already)
public class Counting_Occurences {

    public static void main(String[] args) {


        Scanner input=new Scanner(System.in);
        System.out.println("Enter String");
        String str=input.nextLine();

        int count=0;
        String temp=""; // An empty string to keep track of counted
                                    // characters


        for(int i=0;i<str.length();i++)
        {

            char c=str.charAt(i);  // take one character (c) in string

            for(int j=i;j<str.length();j++)
            {

                char k=str.charAt(j);  
    // take one character (c) and compare with each character (k) in the string
            // also check that character (c) is not already counted.
            // if condition passes then increment the count.
                if(c==k && temp.indexOf(c)==-1)                                                                          
                {

                    count=count+1;

                }

            }

             if(temp.indexOf(c)==-1)  // if it is not already counted
             {


            temp=temp+c; // append the character to the temp indicating
                                         // that you have already counted it.

System.out.println("Character   " + c + "   occurs   " + count + "    times");
             }  
            // reset the counter for next iteration 
              count=0;

        }


    }


}