Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java字数计算程序_Java - Fatal编程技术网

Java字数计算程序

Java字数计算程序,java,Java,我正在尝试制作一个关于字数计算的程序,我已经制作了一部分,它给出了正确的结果,但是当我在字符串中输入空格或多个空格时,字数计算的结果显示错误的结果,因为我是根据使用的空格来计算字数的。我需要帮助,如果有一个解决方案,无论有多少空间,我仍然得到正确的结果。我在下面提到代码 public class CountWords { public static void main (String[] args) { System.out.println("Simp

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

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);
    }
}
公共类CountWords
{
公共静态void main(字符串[]args)
{
println(“简单Java字数计算程序”);
String str1=“今天是霍尔迪日”;
int-wordCount=1;
对于(int i=0;i
您可以使用
String.split
()而不是charAt,您将获得良好的结果。
如果出于某种原因想使用
charAt
,那么在计算字数之前请先尝试,这样您就不会有额外的空间和额外的字数了。一种方法是使用正则表达式。您可以了解有关正则表达式的更多信息。一个好的正则表达式应该是“\w+”,然后计算匹配数

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

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

    }
}
boolean-prevCharWasSpace=true;
对于(int i=0;i
更新
使用拆分技术与这里发生的事情完全相同,但它并不能真正解释它为什么会起作用。如果我们回到CS理论,我们想构造一个有限状态自动机(FSA)来计算字数。该FSA可能显示为:

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

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

String s = "Today is Holdiay Day";
System.out.println("Word count is = " + s.split(" ").length);
其思想是将字符串拆分为任意次数出现的任何空白字符上的单词。 String类的split函数返回一个数组,其中包含作为其元素的单词。
打印数组的长度将得到字符串中的字数。

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

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);
}
publicstaticvoidmain(字符串[]args)
{
println(“简单Java字数计算程序”);
String str1=“今天是霍尔迪日”;
整数计数=0;
字符串[]wCount=str1.split(“”);

对于(int i=0;i您需要逐行读取文件,并将行中出现的多个空格减少为单个空格,然后计算单词数。以下是示例:

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();
}
公共类CountWords
{
公共静态void main(字符串[]args)
{
println(“简单Java字数计算程序”);
String str1=“今天是霍尔迪日”;
int-wordCount=1;
对于(int i=0;i
这会给出正确的结果,因为如果空格出现两次或两次以上,则无法增加字数。请享受。

公共类字数
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));
}
{ 公共静态void main(字符串ar[] { println(“简单Java字数计算程序”); String str1=“今天是霍尔迪日”; int-wordCount=1; 对于(int i=0;i
}

公共类字数
{
公共静态void main(字符串ar[])引发异常
{
println(“简单Java字数计算程序”);
int wordCount=1,count=1;
BufferedReader br=新的BufferedReader(新文件读取器(“C:/file.txt”);
字符串str2=“”,str1=“”;
而((str1=br.readLine())!=null){
str2+=str1;
}
对于(int i=0;i
}

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

公共类字计数器{
公共整数计数(字符串输入){
整数计数=0;
布尔递增计数器=false;
对于(inti=0;i='A'&&c='A'&&c
import com.google.common.base.Optional;
导入com.google.common.base.Splitter;
导入com.google.common.collect.HashMultiset;
导入com.google.common.collect.ImmutableSet;
导入com.google.common.collect.Multiset;
String str=“简单Java字数计算程序”;
Iterable words=Splitter.on(“”.trimResults().split(str);
//谷歌文字计数器
Multiset-wordsMultiset=HashMultiset.create();
对于(字符串:单词){
wordsMultiset.add(string.toLowerCase());
}
Set result=wordsMultiset.elementSet();
for(字符串:结果){
System.out.println(字符串+“X”+wo
 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));
        }
    }   
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));
}
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<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'); 
    }
}
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));
}
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 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");
    }
}
    String data = "This world is mine";
    System.out.print(data.split("\\s+").length);
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);

    }

}
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());
}
    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++;
      }
    }
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());
System.out.println(new StringTokenizer("This    is    a test    app").countTokens());
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 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);
    }
}
    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;
    }
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();