Java word count string

How to Count Number of Words in String ? Java Coding Exercise Example

The string is very popular among the Interviewer, and you are bound to see some questions on any programming interview, Java Interviews are no exception. Questions based on Java fundamentals like why String is Immutable in Java to questions based on coding skills e.g. reverse String using recursion in Java, String has always troubled candidates. In this article, we will see a similar question, how to count the number of words in Java String. Before jumping to the solution, just read below to make sure what a word means here. It’s a sequence of one or more non-space characters.

We will see two examples to find the number of words in Java String, the first one is based upon pure logic, where it goes through all characters from String and then count each word. Second is more interesting than the first one, here we have used a regular expression to find all words.

We split String by white space, passing \\s+ means greedy search i.e. it includes one or more white spaces. BTW, this is one of the questions I forgot to share when I wrote about Top 20 String coding questions, will include it on that list for sure.

Читайте также:  Java xml parser saxparser

Also, basic knowledge of essential data structure and algorithms is also very important and that’s why I suggest all Java programmers join these free Data Structure and Algorithms courses for beginners to improve your knowledge and algorithms skills.

How to Count Number of Words in Given String?

Java program to count number of words in String

Write a function in Java that accepts a string argument and returns the number of words in it. A word is a sequence of one or more non-space characters i.e. any character other than » (empty String). This should be your method signature :

This method should return 5 if passed «Java is best programming language» and return 3 if passed «Java is great». Similarly a call to wordCount(» «) should return 0.

Solution :

In order to implement this method, we need to assume that two words are separated by space. We also need to ignore leading, trailing and multiple spaces between words. One way to solve this problem is to split String by space and then count a number of parts. We will see two solutions of this problem, here is the first one .

How do find a number of words String? 2 Examples

In this sample program, we have two methods, first we will count number of words without using regular expression, and second will do the same but using regex.

/** * Java Program to count number of words in String * * @author Javin */ public class WordCounterProblem< /* * This method return word count without using regular expression */ public int wordcount(String word) < if (word == null || word.isEmpty()) < return 0; > int count = 0; char ch[] = new char[word.length()]; for (int i = 0; i  word.length(); i++) < ch[i] = word.charAt(i); if (((i > 0) && (ch[i] != ' ') && (ch[i - 1] == ' ')) || ((ch[0] != ' ') && (i == 0))) < count++; > > return count; > /* * Counting number of words using regular expression. */ public int countWord(String word) < if (word == null) < return 0; > String input = word.trim(); int count = input.isEmpty() ? 0 : input.split("\\s+").length; return count; > >

Junit Test Case

Whenever you are asked to write code on Interview, make sure you write some unit test as well. Some time Interviewer will ask you explicitly, but many times they just want to see whether the candidate follows development practices like unit testing and code review. For this problem, I have written five tests, though in one method for the sake of brevity.

First is a normal space-separated word, second is empty String, third is String with just space and fourth is word separated with multiple white spaces. You can further add unit tests for null String, String without white space, String with leading and trailing white space. I leave that to you.

import static org.junit.Assert.*; import org.junit.Test; public class WordCounterTest < @Test public void wordCount() < Testing test = new Testing(); assertEquals(3, test.wordcount("JUnit is Best")); // string with three words assertEquals(0, test.wordcount("")); // empty string assertEquals(0, test.wordcount(" ")); // no words, just spaces assertEquals(3, test.wordcount("String is Immutable")); // words with multiple space in between assertEquals(2, test.wordcount("See you ")); // words with trailing space assertEquals(2, test.wordcount(" Good Morning")); // words with leading space assertEquals(0, test.wordcount(null)); // null check > @Test public void countWord() < Testing test = new Testing(); assertEquals(3, test.countWord("JUnit is Best")); assertEquals(0, test.countWord("")); assertEquals(0, test.countWord(" ")); assertEquals(3, test.countWord("String is Immutable")); assertEquals(2, test.countWord("See you ")); assertEquals(2, test.countWord(" Good Morning")); assertEquals(0, test.countWord(null)); > >

That’s all about how to find a number of words in a Java String. We have seen 2 examples to do that. It’s pretty easy using the split() method of the String class, which also accepts regular expressions. By using regex \\s+ we can split String into words. As I said, don’t forget to write unit tests on interviews, Interviewers always expects you to write production-quality code and unit testing is part of that.

  • 30 Programming questions from Job Interviews (list)
  • 15 Data Structure and Algorithm Questions for Programmers (list)
  • Write a Program to solve Producer-Consumer problems in Java. (Solution)
  • How to reverse String in Java without using API methods? (Solution)
  • Write a Program to check if a number is binary in Java? (Solution)
  • How to find the first non-repeated characters from String in Java? (Solution)
  • How to remove duplicates from array without using Collection API? (Solution)
  • Write a Program to Check if a number is Power of Two or not? (Answer)
  • How to Swap Two Numbers without using Temp Variable in Java? (Solution)
  • How to check if LinkedList contains loop in Java? (Solution)
  • How to find the middle element of LinkedList in one pass? (Solution)
  • How to find prime factors of a number in Java? (Solution)
  • Write a Program to prevent Deadlock in Java? (Solution)
  • How to check if a number is a Palindrome or not? (Solution)
  • How to remove duplicates from ArrayList in Java? (Solution)
  • Write a Java Program to See if two String are Anagram of each other? (Solution)
  • How to count occurrences of a character in String? (Solution)
  • Write a Program to calculate Sum of Digits of a number in Java? (Solution)
  • How to check if a number is Prime or not? (Solution)
  • Write a Program to find Fibonacci Series of a Given Number? (Solution)
  • How to check if a number is an Armstrong number or not? (Solution)
  • Write a Program to calculate factorial using recursion in Java? (Solution)
  • How to check if Array contains duplicate numbers or not? (Solution)

Источник

Get Word Count of a String in Java

Get Word Count of a String in Java

  1. Use StringTokenizer to Count Words in a String in Java
  2. Use split() and Regular Expression to Count Words in a String in Java
  3. Get Number of Times a Word Is Repeated in a String in Java

In this article, we are going to shed some light on how to count the number of words in a string in Java and different ways to achieve this.

Use StringTokenizer to Count Words in a String in Java

The StringTokenizer class in Java allows us to break a string into multiple tokens. The methods in this class do not differentiate among quoted strings, identifiers, and numbers, nor do they recognize or skip comments. The characters that separate tokens (delimiters) may be specified either at the time of creation or on a per-token basis.

The StringTokenizer class does not count the whitespace and tabs automatically hence it is handled on its own.

import java.util.StringTokenizer; public class WordCount   public static void main (String args[])  String mydelim = " - ";  String myString = "The sky - - is blue!";  StringTokenizer stringTokenizer1 = new StringTokenizer(myString);  StringTokenizer stringTokenizer2 = new StringTokenizer(myString,mydelim);   int tokensCount1 = stringTokenizer1.countTokens();  int tokensCount2 = stringTokenizer2.countTokens();   System.out.println("Word count without delimiter: "+String.valueOf(tokensCount1));  System.out.println("Word count: "+String.valueOf(tokensCount2));  > > 
Word count without delimiter: 6 Word count: 4 

Here, we have created stringTokenizer1 with passing a string in the constructor, it takes default delimiter whereas for stringTokenizer2 custom delimiter to separate tokens is passed. The first approach does count hyphens while the second doesn’t.

Use split() and Regular Expression to Count Words in a String in Java

The split(String regex) method in Java takes a regular expression and breaks the given string matching the regex and returns an array of strings.

The regular expression we use here is \\s+ which separates the whitespace from the string or in other words it splits the given string around whitespace. The number of words in the string is equal to the length of string array words which we can get by calling length on it. The output shows the number of words in myStr .

public class WordCount   public static void main (String args[])  String myStr = "the butcher's wife, she was from Montreal";  String[] words = myStr.split("\\s+");  System.out.println("Word Count is: "+words.length);  > > 

Get Number of Times a Word Is Repeated in a String in Java

We can calculate the number of times a word is repeated in the given string. Here randomText is a string in which we need to find how many times the word blue is repeated. For this, we take a variable times of type int and initialize it to 0. Run a for loop from 0 to the length of the randomText .

The startsWith() method compares if the string starts with the characters of the given string. For i = 0 the randomText.substring(0) method gets substring at the index 0 and checks if it startsWith(«blue») and if it matches then it will increment times by 1; otherwise, it will not increase.

Similarly, it checks for the rest of the length and prints the number of times the word was repeated in the given string as output.

public class WordCount   public static void main (String args[])  String randomText = "The sky is blue it meets the sea which is also blue";   String text = "blue";  int times = 0;  for (int i = 0; i < randomText.length(); i++)   if (randomText.substring(i).startsWith(text))   times ++;  >  >  System.out.println(randomText + " contains " + text + " " + times + " times");   > > 
The sky is blue it meets the sea which is also blue contains blue 2 times 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java String

Copyright © 2023. All right reserved

Источник

Оцените статью