How To Count Discover Of Words Inward String - Coffee Coding Exercise

String is real pop alongside Interviewer, too yous are boundary to come across roughly questions on whatsoever programming interview, Java Interviews are no exception. Questions based from Java fundamentals similar why String is Immutable inward Java to questions based on coding skills e.g. contrary String using recursion inward Java, String has e'er troubled candidates. In this article, nosotros volition come across a similar questions, how to count publish of words inward Java String. Before jumping to solution, only read below to brand certain what a discussion agency here. It's sequence of ane or to a greater extent than non-space characters. We volition come across 2 examples to honour publish of words inward Java String, kickoff ane is based upon pure logic, where it goes through all characters from String too and then count each word. Second is to a greater extent than interesting than kickoff one, hither nosotros create got used regular facial expression to honour all words. We split upwards String yesteryear white space, passing \\s+ means greedy search i.e. it includes ane or to a greater extent than white spaces.  BTW, this is ane of the enquiry I forgot to part when I wrote virtually Top twenty String coding questions, volition include it on that listing for sure.


Problem :

 String is real pop alongside Interviewer How to Count Number of Words inward String - Java Coding ExerciseWrite a portion inward Java which convey a String declaration too returns publish of words inward it. Influenza A virus subtype H5N1 discussion is a sequence of ane or to a greater extent than non-space grapheme i.e. whatsoever grapheme other than '' (empty String). This should endure your method signature :


public int wordCount(String word);

This method should provide 5 if passed "Java is best programming language" too provide 3 if passed "Java is great". Similarly a telephone telephone to wordCount("    ") should provide 0.

Solution :

In gild to implement this method nosotros demand to assume that 2 words are separated yesteryear space. We likewise demand to ignore leading, trailing too multiple spaces betwixt words. One way to solve this work is  to split upwards String yesteryear infinite too and then count publish of parts. We volition come across 2 solution of this problem, hither is the kickoff ane .


How honour publish of words String - 2 Examples

In this sample program, nosotros create got 2 methods, kickoff nosotros volition count publish of words without using regular expression, too minute volition create the same but using regex.

/**  * Java Program to count publish of words inward String  *  * @author  Javin  */ public class WordCounterProblem{         /*     * This method provide discussion count without using regular facial 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 publish 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 yous are asked to write code on Interview, brand certain yous write roughly unit of measurement seek equally well. Some fourth dimension Interviewer volition inquire yous explicitly, but many times they only desire to come across whether candidate follows evolution do similar unit of measurement testing too code review. For this problem, I create got wrote 5 test, though inward ane method for the sake of brevity. First is a normal infinite separated word, minute is empty String, 3rd is String with only infinite too 4th is discussion separated with multiple white space. You tin farther add together unit of measurement seek for nil String, String without white space, String with leading too trailing white space. I larn out 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 3 words         assertEquals(0, test.wordcount(""));  // empty string         assertEquals(0, test.wordcount("   "));  // no words, only spaces         assertEquals(3, test.wordcount("String   is   Immutable")); // words with multiple infinite inward between         assertEquals(2, test.wordcount("See yous     ")); // words with trailing space         assertEquals(2, test.wordcount("  Good Morning")); // words with leading space         assertEquals(0, test.wordcount(null)); // nil 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 yous     "));         assertEquals(2, test.countWord("  Good Morning"));         assertEquals(0, test.countWord(null));     }  }

That's all virtually how to honour publish of words inward a Java String. We create got seen 2 examples to create that. It's pretty slow using split() method of String class, which likewise accepts regular expression. By using regex \\s+ nosotros tin split upwards String into words. As I said, don't forget to write unit of measurement seek on interviews, Interviewer e'er seem yous to write production character code too unit of measurement testing is portion of that.

Further Reading
Algorithms too Data Structures - Part 1 too 2
Java Fundamentals, Part 1 too 2
Cracking the Coding Interview - 189 Questions too Solutions

If yous similar this coding work too hungry for to a greater extent than coding questions from Interviews, cheque out these amazing collection :
  • 30 Programming questions from Job Interviews (list)
  • 15 Data Structure too Algorithm Questions for Programmers (list)
  • Write a Program to solve Producer Consumer Problem inward Java. (Solution)
  • How to contrary String inward Java without using API methods? (Solution)
  • Write a Program to cheque if a publish is binary inward Java? (Solution)
  • How to honour kickoff non repeated characters from String inward Java? (Solution)
  • How to take duplicates from array without using Collection API? (Solution)
  • Write a Program to Check if a publish is Power of Two or not? (Answer)
  • How to Swap Two Numbers without using Temp Variable inward Java? (Solution)
  • How to cheque if LinkedList contains loop inward Java? (Solution)
  • How to honour pump chemical cistron of LinkedList inward ane pass? (Solution)
  • How to honour prime number factors of a publish inward Java? (Solution)
  • Write a Program to foreclose Deadlock inward Java? (Solution)
  • How to cheque if a publish is Palindrome or not? (Solution)
  • How to take duplicates from ArrayList inward Java? (Solution)
  • Write a Java Program to See if 2 String are Anagram of each other? (Solution)
  • How to count occurrences of  a grapheme inward String? (Solution)
  • Write a Program to calculate Sum of Digits of a publish inward Java? (Solution)
  • How to cheque if a publish is Prime or not? (Solution)
  • Write a Program to honour Fibonacci Series of a Given Number? (Solution)
  • How to cheque if a publish is Armstrong publish or not? (Solution)
  • Write a Program to calculate factorial using recursion inward Java? (Solution)
  • How to cheque if Array contains duplicate publish or not? (Solution)

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures too Algorithms: Deep Dive Using Java
Algorithms too Data Structures - Part 1 too 2


Sumber https://javarevisited.blogspot.com/

0 Response to "How To Count Discover Of Words Inward String - Coffee Coding Exercise"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel