English 中文(简体)
计算字符串字符串中字符的发生次数 [重复]
原标题:Counting the number of occurences of characters in a string [duplicate]

我试图写入一个 Java 程序, 它将输入字符串, 并计算字符串中字符的发生次数, 然后打印一个字符串, 其字符后面是无字符 。

E.G.

输入字符串 :

aaaabb

输出字符串 :

a4b2

输入字符串 :

aaaaabbbc

输出字符串 :

a5b3c1

I am posting my java code.
It is throwing 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);
    }

}

}
问题回答

这就是问题所在:

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

i 与字符串的长度相同时,它会要求字符在字符串的结尾之外。 您可能想要 :

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

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

count = count + i;

对其中之一:

count++;

... 或除去 count < i > /code>。 毕竟它们总是具有相同的价值。 个人而言, 我只需要使用一个变量, 声明和初始化的 旁的 < em > / em > 循环。 这是一个一般的样式点, 事实上, 当本地变量需要时, 它更干净, 而不是在方法的顶部声明它们全部 。

然而,你的程序会永远循环下去, 因为这没有任何用处:

str.substring(count);

Java - substring 返回一个 new 字符串。

str = str.substring(count);

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

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

我不想提供完整的代码。所以我想给你一个挑战,玩得开心。我鼓励你简化代码,只有1个循环。

基本上, 我的想法是将字符比较对齐, 并排。 例如, 比较字符 1 和 查尔 2 、 查尔 2 和 查尔 3 等。 当查尔 N 和 查尔( N+1 ) 不同时, 重置字符数 。 您可以将字符数重新设置为一个循环 。 在处理此选项时, 将设置新的字符串 。 不要使用相同的字符串作为输入 。 这令人困惑 。

记住,让事情简单计数。开发商的生活足够难看复杂的代码。

玩得开心点!

Tommy "我应该当老师" Kwee

如果这是一个真正的方案,而不是一个研究项目,那么请使用阿帕奇公域 < a href="http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html" rel=“nofollow'>StringUtils 类 - 特别是计数马切斯方法。

如果这是一个研究项目,那么就保留它,并从你的探索中学习:)

我想你要找的是这个:

公共类 问题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);
时 时

时 时

尝试此 :

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;

        }


    }


}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...