【问题标题】:Java word count programJava字数统计程序
【发布时间】:2011-11-12 05:29:06
【问题描述】:

我正在尝试编写一个我已经部分完成的字数统计程序,它给出了正确的结果,但是当我在字符串中输入空格或多个空格时,字数统计结果显示错误的结果,因为我我根据使用的空格计算单词。如果有一个解决方案,无论有多少空间,我仍然可以得到正确的结果,我需要帮助。我提到下面的代码。

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

            System.out.println("Simple Java Word Count Program");

            String str1 = "Today is Holdiay Day";

            int wordCount = 1;

            for (int i = 0; i < str1.length(); i++) 
            {
                if (str1.charAt(i) == ' ') 
                {
                    wordCount++;
                } 
            }

            System.out.println("Word count is = " + wordCount);
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:
    public static void main (String[] args) {
    
         System.out.println("Simple Java Word Count Program");
    
         String str1 = "Today is Holdiay Day";
    
         String[] wordArray = str1.trim().split("\\s+");
         int wordCount = wordArray.length;
    
         System.out.println("Word count is = " + wordCount);
    }
    

    想法是将字符串拆分为任何出现任意次数的空白字符上的单词。 String 类的 split 函数返回一个包含单词作为其元素的数组。 打印数组的长度将产生字符串中的单词数。

    【讨论】:

    • 你能否让程序更简单,只使用 if else 语句和 for 循环
    • 我不确定我能否关注您的评论。这能得到什么更简单的东西。更不用说引入 if-else 语句和 for 循环肯定会使程序变得更长和效率低下。
    • Split 将返回数组。 String[] wordArray = str1.split("\\s+");
    【解决方案2】:

    为此有两条路线。一种方法是使用正则表达式。你可以找到更多关于正则表达式here。一个好的正则表达式是这样的 "\w+" 然后计算匹配的数量。

    如果你不想走那条路,你可以有一个布尔标志来记住你看到的最后一个字符是否是空格。如果是,就不要计较了。所以循环的中心是这样的:

    boolean prevCharWasSpace=true;
    for (int i = 0; i < str1.length(); i++) 
    {
        if (str1.charAt(i) == ' ') {
            prevCharWasSpace=true;
        }
    else{
            if(prevCharWasSpace) wordChar++;
            prevCharWasSpace = false;
    
        }
    }
    

    更新
    使用拆分技术与这里发生的事情完全相同,但它并不能真正解释它为什么起作用。如果我们回到我们的 CS 理论,我们想要构建一个计算单词的有限状态自动机 (FSA)。该 FSA 可能显示为:

    如果您查看代码,它会准确地实现这个 FSA。 prevCharWasSpace 跟踪我们所处的状态,而 str1.charAt('i') 决定正在跟随哪条边(或箭头)。如果使用 split 方法,则在内部构造一个与此 FSA 等效的正则表达式,用于将字符串拆分为数组。

    【讨论】:

    • 嘿,谢谢老兄,效果很好,但是除了使用两个 if 之外,还有其他方法吗
    • 这显示错误的结果。如果我在单词“day”之前多放一个空格。它显示 3。它应该显示 4。对吧,先生?
    • 你能澄清一下这条线是做什么的吗-- if(!prevCharWasSpace)
    • 是的,你是对的,但你可以用值 1 声明 wordCount 变量
    【解决方案3】:

    Java 确实有 StringTokenizer API,可用于此目的,如下所示。

    String test = "This is a test app";
    int countOfTokens = new StringTokenizer(test).countTokens();
    System.out.println(countOfTokens);
    

    单行如下

    System.out.println(new StringTokenizer("This is a test app").countTokens());
    

    StringTokenizer 支持输入字符串中的多个空格,只计算修剪不必要空格的单词。

    System.out.println(new StringTokenizer("This    is    a test    app").countTokens());
    

    上面的行也打印 5

    【讨论】:

      【解决方案4】:

      你可以用String.split(read more here)代替charAt,你会得到很好的效果。 如果您出于某种原因想使用charAt,请在计算单词之前尝试trimming the string,这样您就不会有多余的空格和多余的单词

      【讨论】:

      • 修剪字符串将删除字符串开头和结尾的空格,因此如果单词之间有多个空格,问题仍然存在。此外,使用String.split 会创建一个String[],因此如果输入很大,您最终会使用大量 内存。
      • 但不会使用 String.split 比使用循环逐个字符地遍历大字符串更有效,我不是说你错了,我只是在问一个问题跨度>
      • String.split 在后台使用正则表达式引擎,因此与String 上的简单逐字符迭代相比,它实际上做了很多 处理. (返回值是一个String[],其中包含新创建的Strings。)我在这里看到的最有效的实现可能与@heneryville 的答案一致。几乎不使用任何额外的内存,并且执行绝对最少的处理。
      【解决方案5】:

      我的实现,没有使用 StringTokenizer:

      Map<String, Long> getWordCounts(List<String> sentences, int maxLength) {
          Map<String, Long> commonWordsInEventDescriptions = sentences
              .parallelStream()
              .map(sentence -> sentence.replace(".", ""))
              .map(string -> string.split(" "))
              .flatMap(Arrays::stream)
              .map(s -> s.toLowerCase())
              .filter(word -> word.length() >= 2 && word.length() <= maxLength)
              .collect(groupingBy(Function.identity(), counting()));
          }
      

      那么,你可以这样称呼它,例如:

      getWordCounts(list, 9).entrySet().stream()
                      .filter(pair -> pair.getValue() <= 3 && pair.getValue() >= 1)
                      .findFirst()
                      .orElseThrow(() -> 
          new RuntimeException("No matching word found.")).getKey();
      

      也许翻转方法返回Map&lt;Long, String&gt;可能会更好。

      【讨论】:

        【解决方案6】:

        使用split(regex) 方法。结果是一个被regex分割的字符串数组。

        String s = "Today is Holdiay Day";
        System.out.println("Word count is = " + s.split(" ").length);
        

        【讨论】:

          【解决方案7】:

          您需要逐行读取文件并将出现在您的行中的空格的多次出现减少为一次出现,然后计算单词。以下是一个示例:

          public static void main(String... args) throws IOException {   
          
              FileInputStream fstream = new FileInputStream("c:\\test.txt");
              DataInputStream in = new DataInputStream(fstream);
              BufferedReader br = new BufferedReader(new InputStreamReader(in));
              String strLine;
              int wordcount = 0;
              while ((strLine = br.readLine()) != null)   {
                  strLine = strLine.replaceAll("[\t\b]", "");
                  strLine = strLine.replaceAll(" {2,}", " ");
                  if (!strLine.isEmpty()){
                      wordcount = wordcount + strLine.split(" ").length;
                  }
              }
          
              System.out.println(wordcount);
              in.close();
          }
          

          【讨论】:

          • 我只想通过简单的 if else 语句和 for 循环来完成
          • 在这种情况下,请查看@heneryville 的建议。您可以检查所有空格,而不仅仅是空格。
          【解决方案8】:
          public class wordCOunt
          {
          public static void main(String ar[])
          {
          System.out.println("Simple Java Word Count Program");
          
              String str1 = "Today is Holdiay Day";
          
              int wordCount = 1;
          
              for (int i = 0; i < str1.length(); i++) 
              {
                  if (str1.charAt(i) == ' '&& str1.charAt(i+1)!=' ') 
                  {
                      wordCount++;
                  } 
              }
          
              System.out.println("Word count is = " +(str1.length()- wordCount));
          }
          

          }

          【讨论】:

            【解决方案9】:
            public class wordCount
            {
            public static void main(String ar[]) throws Exception
            {
            System.out.println("Simple Java Word Count Program");
            
            
                int wordCount = 1,count=1;
             BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
                        String str2 = "", str1 = "";
            
                        while ((str1 = br.readLine()) != null) {
            
                                str2 += str1;
            
                        }
            
            
                for (int i = 0; i < str2.length(); i++) 
                {
                    if (str2.charAt(i) == ' ' && str2.charAt(i+1)!=' ') 
                    {
                        wordCount++;
                    } 
            
            
                    }
            
                System.out.println("Word count is = " +(wordCount));
            }
            

            }

            【讨论】:

              【解决方案10】:

              您应该通过考虑其他单词分隔符来使您的代码更通用..例如“,”“;”等等

              public class WordCounter{
                  public int count(String input){
                      int count =0;
                      boolean incrementCounter = false;
                      for (int i=0; i<input.length(); i++){
                          if (isValidWordCharacter(input.charAt(i))){
                              incrementCounter = true;
                          }else if (incrementCounter){
                              count++;
                              incrementCounter = false;
                          }
                      }
                      if (incrementCounter) count ++;//if string ends with a valid word
                      return count;
                  }
                  private boolean isValidWordCharacter(char c){
                      //any logic that will help you identify a valid character in a word
                      // you could also have a method which identifies word separators instead of this
                      return (c >= 'A' && c<='Z') || (c >= 'a' && c<='z'); 
                  }
              }
              

              【讨论】:

                【解决方案11】:
                import com.google.common.base.Optional;
                import com.google.common.base.Splitter;
                import com.google.common.collect.HashMultiset;
                import com.google.common.collect.ImmutableSet;
                import com.google.common.collect.Multiset;
                
                String str="Simple Java Word Count count Count Program";
                Iterable<String> words = Splitter.on(" ").trimResults().split(str);
                
                
                //google word counter       
                Multiset<String> wordsMultiset = HashMultiset.create();
                for (String string : words) {   
                    wordsMultiset.add(string.toLowerCase());
                }
                
                Set<String> result = wordsMultiset.elementSet();
                for (String string : result) {
                    System.out.println(string+" X "+wordsMultiset.count(string));
                }
                

                【讨论】:

                  【解决方案12】:
                  public static int CountWords(String str){
                  
                     if(str.length() == 0)
                            return 0;
                  
                     int count =0;
                     for(int i=0;i< str.length();i++){
                  
                  
                        if(str(i) == ' ')
                            continue;
                  
                        if(i > 0 && str.charAt(i-1) == ' '){
                          count++;
                        } 
                  
                        else if(i==0 && str.charAt(i) != ' '){
                         count++;
                        }
                  
                  
                     }
                     return count;
                  
                  }
                  

                  【讨论】:

                    【解决方案13】:
                     public class CountWords 
                        {
                            public static void main (String[] args)
                            {
                                System.out.println("Simple Java Word Count Program");
                                String str1 = "Today is Holdiay Day";
                                int wordCount = 1;
                                for (int i = 0; i < str1.length(); i++) 
                                {
                                    if (str1.charAt(i) == ' ' && str1.charAt(i+1)!=' ') 
                                    {
                                        wordCount++;
                                    } 
                                }
                                System.out.println("Word count is = " + wordCount));
                            }
                        }   
                    

                    这给出了正确的结果,因为如果空间出现两次或更多,则它不能增加字数。享受吧。

                    【讨论】:

                      【解决方案14】:

                      试试这个

                      import java.util.ArrayList;
                      import java.util.Collections;
                      import java.util.HashMap;
                      import java.util.List;
                      import java.util.Map;
                      public class wordcount {
                          public static void main(String[] args) {
                              String s = "India is my country. I love India";
                              List<String> qw = new ArrayList<String>();
                              Map<String, Integer> mmm = new HashMap<String, Integer>();
                              for (String sp : s.split(" ")) {
                                  qw.add(sp);
                              }
                              for (String num : qw) {
                                  mmm.put(num, Collections.frequency(qw, num));
                              }
                              System.out.println(mmm);
                      
                          }
                      
                      }
                      

                      【讨论】:

                        【解决方案15】:

                        统计总字数或统计总字数而不重复字数

                        public static void main(String[] args) {
                            // TODO Auto-generated method stub
                            String test = "I am trying to make make make";
                            Pattern p = Pattern.compile("\\w+");
                            Matcher m = p.matcher(test);
                            HashSet<String> hs =  new HashSet<>();
                            int i=0;
                            while (m.find()) {
                                i++;
                                hs.add(m.group());
                            }
                            System.out.println("Total words Count==" + i);
                            System.out.println("Count without Repetation ==" + hs.size());
                        }
                        

                        }

                        输出:

                        总字数==7

                        不重复计数 ==5

                        【讨论】:

                          【解决方案16】:

                          不确定是否有缺点,但这对我有用...

                              Scanner input = new Scanner(System.in);
                              String userInput = input.nextLine();
                              String trimmed = userInput.trim();
                              int count = 1;
                          
                              for (int i = 0; i < trimmed.length(); i++) {
                                if ((trimmed.charAt(i) == ' ') && (trimmed.charAt(i-1) != ' ')) {
                                  count++;
                                }
                              }
                          

                          【讨论】:

                            【解决方案17】:

                            您可以使用此代码。它可以帮助您:

                            public static void main (String[] args)
                            {
                            
                               System.out.println("Simple Java Word Count Program");
                            
                               String str1 = "Today is Holdiay Day";
                               int count=0;
                               String[] wCount=str1.split(" ");
                            
                               for(int i=0;i<wCount.length;i++){
                                    if(!wCount[i].isEmpty())
                                    {
                                        count++;
                                    }
                               }
                               System.out.println(count);
                            }
                            

                            【讨论】:

                            • 您的代码运行良好,但您能帮我通过简单的 if else 语句和 for 循环来完成它吗?
                            【解决方案18】:
                                String data = "This world is mine";
                                System.out.print(data.split("\\s+").length);
                            

                            【讨论】:

                              【解决方案19】:

                              这可以像使用 split 和 count 变量一样简单。

                              public class SplitString {
                              
                                  public static void main(String[] args) {
                                      int count=0;        
                                      String s1="Hi i love to code";
                              
                                      for(String s:s1.split(" "))
                                      {
                                          count++;
                                      }
                                      System.out.println(count);
                                  }
                              }
                              

                              【讨论】:

                                【解决方案20】:
                                    public class TotalWordsInSentence {
                                    public static void main(String[] args) {
                                
                                        String str = "This is sample sentence";
                                        int NoOfWOrds = 1;
                                
                                        for (int i = 0; i<str.length();i++){
                                            if ((str.charAt(i) == ' ') && (i!=0) && (str.charAt(i-1) != ' ')){
                                                NoOfWOrds++;
                                            }
                                        }
                                         System.out.println("Number of Words in Sentence: " + NoOfWOrds);
                                    }
                                }
                                

                                在这段代码中,其中的空白不会有任何问题。
                                只是简单的 for 循环。希望这会有所帮助...

                                【讨论】:

                                  【解决方案21】:

                                  只计算指定的单词,例如 John、John99、John_John 和 John's only。根据自己更改正则表达式并仅计算指定的单词。

                                      public static int wordCount(String content) {
                                          int count = 0;
                                          String regex = "([a-zA-Z_’][0-9]*)+[\\s]*";     
                                          Pattern pattern = Pattern.compile(regex);
                                          Matcher matcher = pattern.matcher(content);
                                          while(matcher.find()) {
                                              count++;
                                              System.out.println(matcher.group().trim()); //If want to display the matched words
                                          }
                                          return count;
                                      }
                                  

                                  【讨论】:

                                    【解决方案22】:

                                    完整的程序是:

                                    public class main {
                                    
                                        public static void main(String[] args) {
                                    
                                            logicCounter counter1 = new logicCounter();
                                            counter1.counter("I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.");
                                        }
                                    }
                                    
                                    public class logicCounter {
                                    
                                        public void counter (String str) {
                                    
                                            String str1 = str;
                                            boolean space= true;
                                            int i;
                                    
                                            for ( i = 0; i < str1.length(); i++) {
                                    
                                                if (str1.charAt(i) == ' ') {
                                                    space=true;
                                                } else {
                                                    i++;
                                                }
                                            }
                                    
                                            System.out.println("there are " + i + " letters");
                                        }
                                    }
                                    

                                    【讨论】:

                                    • 这似乎是计算字母而不是单词,OP 要求计算字数。
                                    猜你喜欢
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2012-05-03
                                    • 2012-04-19
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    相关资源
                                    最近更新 更多