Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count words in a string method?

I was wondering how I would write a method to count the number of words in a java string only by using string methods like charAt, length, or substring.

Loops and if statements are okay!

I really appreciate any help I can get! Thanks!

like image 462
Philip McQuitty Avatar asked May 03 '11 01:05

Philip McQuitty


People also ask

How do you count words in a string in Python?

Use the count() Method to Count Words in Python String Python. The count() method is a Python built-in method. It takes three parameters and returns the number of occurrences based on the given substring.

How do you count words in a string array?

Instantiate a String class by passing the byte array to its constructor. Using split() method read the words of the String to an array. Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.


2 Answers

This would work even with multiple spaces and leading and/or trailing spaces and blank lines:

String trim = s.trim(); if (trim.isEmpty())     return 0; return trim.split("\\s+").length; // separate string around spaces 

Hope that helps. More info about split here.

like image 145
Cory G. Avatar answered Oct 06 '22 01:10

Cory G.


public static int countWords(String s){      int wordCount = 0;      boolean word = false;     int endOfLine = s.length() - 1;      for (int i = 0; i < s.length(); i++) {         // if the char is a letter, word = true.         if (Character.isLetter(s.charAt(i)) && i != endOfLine) {             word = true;             // if char isn't a letter and there have been letters before,             // counter goes up.         } else if (!Character.isLetter(s.charAt(i)) && word) {             wordCount++;             word = false;             // last word of String; if it doesn't end with a non letter, it             // wouldn't count without this.         } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {             wordCount++;         }     }     return wordCount; } 
like image 36
koool Avatar answered Oct 06 '22 02:10

koool