Java-woordentellingsprogramma

Ik probeer een programma te maken over het aantal woorden dat ik gedeeltelijk heb gemaakt en het geeft het juiste resultaat, maar op het moment dat ik een spatie of meer dan één spatie in de string invoer, geeft het resultaat van het aantal woorden verkeerde resultaten omdat ik Ik tel woorden op basis van de gebruikte spaties. Ik heb hulp nodig als er een oplossing is op een manier dat ik, ongeacht het aantal spaties, toch het juiste resultaat krijg. Ik vermeld de onderstaande code.

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

Antwoord 1, autoriteit 100%

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

Het idee is om de string in woorden te splitsen op elk willekeurig aantal keren dat een spatie voorkomt.
De functie split van de klasse String retourneert een array die de woorden als elementen bevat.
Het afdrukken van de lengte van de array zou het aantal woorden in de string opleveren.


Antwoord 2, autoriteit 70%

Twee routes hiervoor. Een manier zou zijn om reguliere expressies te gebruiken. U kunt hiermeer informatie vinden over reguliere expressies. Een goede reguliere expressie hiervoor zou zoiets zijn als “\w+”. Tel vervolgens het aantal overeenkomsten.

Als je die route niet wilt gaan, kun je een booleaanse vlag hebben die onthoudt of het laatste teken dat je hebt gezien een spatie is. Als dat zo is, tel het dan niet. Dus het midden van de lus ziet er als volgt uit:

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

Bijwerken
Het gebruik van de splittechniek is exact gelijk aan wat hier gebeurt, maar het verklaart niet echt waarom het werkt. Als we teruggaan naar onze CS-theorie, willen we een Finite State Automa (FSA) construeren dat woorden telt. Die FSA kan verschijnen als:
voer hier de afbeeldingsbeschrijving in

Als je naar de code kijkt, implementeert deze deze FSA precies. De prevCharWasSpace houdt bij in welke staat we ons bevinden, en de str1.charAt(‘i’) bepaalt welke rand (of pijl) wordt gevolgd. Als u de split-methode gebruikt, wordt intern een reguliere expressie-equivalent van deze FSA geconstrueerd en gebruikt om de string in een array te splitsen.


Antwoord 3, autoriteit 20%

Java heeft wel StringTokenizerAPI en kan voor dit doel worden gebruikt zoals hieronder.

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

OF

in een enkele regel zoals hieronder

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

StringTokenizerondersteunt meerdere spaties in de invoertekenreeks, waarbij alleen de woorden worden geteld die onnodige spaties bijsnijden.

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

Bovenstaande regel drukt ook 5 af


Antwoord 4, autoriteit 15%

U kunt String.splitgebruiken (lees hier meer) in plaats van charAt, krijgt u goede resultaten.
Als je om de een of andere reden charAtwilt gebruiken, probeer dan de string inkortenvoordat je de woorden telt, op die manier heb je geen extra spatie en een extra woord


Antwoord 5, autoriteit 5%

Mijn implementatie, zonder 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()));
    }

Je zou het dan als voorbeeld kunnen noemen:

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

Misschien is het beter om de methode om te keren om Map<Long, String>te retourneren.


Antwoord 6

Gebruik de split(regex)-methode. Het resultaat is een reeks strings die is opgesplitst door regex.

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

Antwoord 7

Je moet het bestand regel voor regel lezen en het aantal voorkomens van de spaties die in je regel verschijnen tot één enkel voorkomen verminderen en dan tellen voor de woorden. Hieronder volgt een voorbeeld:

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

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

}


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

}


Antwoord 10

u zou uw code algemener moeten maken door ook andere woordscheidingstekens te overwegen.. zoals “,” “;” enz.

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

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

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

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

Dit geeft het juiste resultaat, want als de spatie twee keer of meer komt, kan het aantal woorden niet toenemen. Geniet ervan.


Antwoord 14

probeer dit

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

Antwoord 15

Totaal aantal woorden tellen Of totaal aantal woorden tellen zonder herhaalde woordentelling

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

}

Uitvoer:

Totaal aantal woorden ==7

Tellen zonder herhaling ==5


Antwoord 16

Ik weet niet zeker of er een nadeel is, maar dit werkte voor mij…

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

Antwoord 17

U kunt deze code gebruiken. Het kan u helpen:

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

Antwoord 18

   String data = "This world is mine";
    System.out.print(data.split("\\s+").length);

Antwoord 19

Dit kan net zo eenvoudig zijn als het gebruik van de variabele splitsen en tellen.

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

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

In deze code zal er geen probleem zijn met betrekking tot witruimte erin.
gewoon de simpele for-lus. Ik hoop dat dit helpt…


Antwoord 21

Alleen opgegeven woorden tellen, zoals John, John99, John_John en alleen die van John. Verander de regex naar eigen inzicht en tel alleen de gespecificeerde woorden.

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

Antwoord 22

Het volledige programma werkt:

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

Other episodes