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

これが問題です:

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

それは最後から落ちるまで続きます...iが文字列の長さと同じ場合、文字列の最後を超える文字を要求します。あなたはおそらく欲しい:

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

また、より大きなループの各反復の開始時に 0 に設定する必要がありcountます - 結局、カウントはリセットされます - そして変更します

count = count + i;

次のいずれかに:

count++;

count...またはまたはを取り除きiます。結局のところ、それらは常に同じ値を持つことになります。個人的には、ループで宣言および初期化された 1 つの変数を使用するだけです。実際、これは一般的なスタイル ポイントです。メソッドの先頭ですべてを宣言するよりも、必要なときにローカル変数を宣言する方がクリーンです。

ただし、これでは何も役に立たないため、プログラムは永遠にループします。

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) と同じでない場合、文字数をリセットします。これは 1 回のループでのみ実行できます。これを処理しながら、新しい文字列を形成します。入力と同じ文字列を使用しないでください。それは紛らわしいです。

物事をシンプルにすることが重要であることを忘れないでください。開発者にとって、複雑なコードを見ているだけでも大変です。

楽しむ!

トミー「I should be a Teacher」Kwee

于 2012-05-25T06:49:30.740 に答える
0

これが実際のプログラムであり、研究プロジェクトではない場合は、Apache Commons のStringUtilsクラス (特に countMatches メソッド) の使用を検討してください。

それが研究プロジェクトである場合は、それを続けて、探索から学びましょう :)

于 2012-05-25T06:57:31.937 に答える
-1

あなたが探しているのはこれだと思います:

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

}

于 2014-01-10T14:45:55.103 に答える
-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", ".");
于 2012-05-25T05:59:18.847 に答える
-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 に答える