Java字数统计程序

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

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

 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函数返回一个包含单词作为其元素的数组。 打印数组的长度将产生字符串中的单词数。

两条路线。 一种方法是使用正则表达式。 您可以在此处找到有关正则表达式的更多信息 一个很好的正则表达式就像“\ 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的正则表达式,并将其用于将字符串拆分为数组。

你可以使用String.split ( 在这里阅读更多 )而不是charAt,你会得到很好的结果。 如果你想出于某些原因使用charAt ,那么在计算单词之前尝试修剪字符串 ,这样就不会有额外的空间和额外的单词

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

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

}

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

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

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

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

}

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

 public class WordCounter{ public int count(String input){ int count =0; boolean incrementCounter = false; for (int i=0; i= 'A' && c<='Z') || (c >= 'a' && c<='z'); } } 
 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 words = Splitter.on(" ").trimResults().split(str); //google word counter Multiset wordsMultiset = HashMultiset.create(); for (String string : words) { wordsMultiset.add(string.toLowerCase()); } Set result = wordsMultiset.elementSet(); for (String string : result) { System.out.println(string+" X "+wordsMultiset.count(string)); } 
 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; } 
  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)); } } 

这给出了正确的结果,因为如果空间来了两次或更多,则它不能增加wordcount。 请享用。

尝试这个

 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 qw = new ArrayList(); Map mmm = new HashMap(); for (String sp : s.split(" ")) { qw.add(sp); } for (String num : qw) { mmm.put(num, Collections.frequency(qw, num)); } System.out.println(mmm); } } 

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

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

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

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

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

 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 
  String data = "This world is mine"; System.out.print(data.split("\\s+").length); 

这可以像使用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); } } 

完整的计划是:

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