【问题标题】:Counting the number of occurences of characters in a string [duplicate]计算字符串中字符的出现次数[重复]
【发布时间】:2012-05-31 17:26:45
【问题描述】:

我正在尝试编写一个 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);
    }

}

}

【问题讨论】:

  • 添加算法标签怎么样?对于小组来说,这实际上是一个简单的问题。这个问题看起来像是一个面试问题,也是一个标签。

标签: java string exception string-parsing


【解决方案1】:

这就是问题所在:

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”。可以吗?

【讨论】:

  • 那我怎么比较字符是否相同..
  • 即使这样它也给出了同样的例外..
  • @user1262062:确实不应该。你确定你已经重建了代码?
  • @user1262062:我想我现在已经给了你足够多的提示了。我认为这是家庭作业——我已经告诉了你修复它所需的一切。您需要自己努力找出问题所在 - 如果我只是给您完整的代码,您不会学到很多东西,对吗? (我还强烈建议您使用完整的单词进行交流,而不是使用“文字说话”,这会使每个人的生活变得更加困难。交流在软件工程中非常重要。)
  • 如果这是你面试的答案,你必须用最好和最简单的代码给公司留下深刻印象。可能无法期望完美,但我知道有一个更简单的代码解决方案(请参阅下面的答案)。链接位于 www.careercup.com。
【解决方案2】:

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

public static int countMatches(String str, 字符串子)

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

尝试以下方法:

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

【讨论】:

  • 不是真的 - 你还没有说StringUtils 来自哪里,我怀疑这个问题的目的是学习
  • 对不起.. 我以前从未使用过它.. 倒是你告诉 hw 使用它..
【解决方案3】:

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

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

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

玩得开心!

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

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

    • StringUtils 的自动空值检查也是一个很棒的东西。
    【解决方案5】:

    试试这个:

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

    【讨论】:

    • 不只是提供代码,您应该尝试解释您所做的事情,以便提问的人可以学习,而不仅仅是复制您的代码。
    【解决方案6】:

    我认为您正在寻找的是:

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

    }

    【讨论】:

      【解决方案7】:
      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);         
      }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-03-02
        • 2020-06-14
        • 1970-01-01
        • 2013-11-04
        • 1970-01-01
        • 1970-01-01
        • 2014-04-24
        相关资源
        最近更新 更多