0

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

例如

输入字符串:

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);
    }

}

}
4

7 回答 7

3
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);         
}
}
于 2014-08-26T07:28:46.427 回答
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返回一个字符串。我想你想要:

str = str.substring(count);

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

于 2012-05-25T05:58:43.640 回答
2

我不想给出完整的代码。所以我想给你挑战并从中获得乐趣。我鼓励您使代码更简单,并且只有 1 个循环。

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

请记住,让事情变得简单很重要。看着复杂的代码,开发人员的生活已经够难了。

玩得开心!

汤米“我应该成为一名老师”奎

于 2012-05-25T06:49:30.740 回答
0

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

如果这是一个学习项目,那就坚持下去,从你的探索中学习:)

于 2012-05-25T06:57:31.937 回答
-1

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

公共静态 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", ".");
于 2012-05-25T05:59:18.847 回答
-1

我认为您正在寻找的是:

公共类问题2 {

/**
 * @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);
}

}

于 2014-01-10T14:45:55.103 回答
-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;

        }


    }


}
于 2013-12-24T10:45:21.803 回答