You tin count words inwards Java String yesteryear using the split() method of String. H5N1 discussion is nil but a non-space grapheme inwards String, which is separated yesteryear i or multiple spaces. By using regular human face to let on spaces in addition to divide on them volition give y'all an array of all words inwards given String. This was the slow agency to solve this job equally shown here, but if y'all accept been asked to write a plan to count a pose out of words inwards given String inwards Java without using whatsoever of String utility methods similar String.split() or StringTokenizer in addition to so it's a niggling fleck challenging for a beginner programmer. It's truly i of the mutual Java coding questions in addition to I accept seen it a twosome of times alongside Java developer interviews of 2 to four years of experience. The interviewer pose additional constraints similar split() is non allowed, y'all tin exclusively work basic methods similar charAt(), length(), in addition to substring() along alongside loop, operators, in addition to other basic programming tools.
In this article, I'll portion all 3 ways to solve this job i.e. commencement yesteryear using String's split() method in addition to regular expression, minute yesteryear using StringTokenizer in addition to tertiary without using whatsoever library method similar above. The tertiary i is the most interesting in addition to really hard to write a consummate solution treatment all exceptional characters e.g. non-printable ASCII characters. for our purpose, nosotros assume that infinite grapheme includes tab, infinite or novel business in addition to anything which is considered equally a missive of the alphabet yesteryear Character.isLetter() is considered equally a word.
Btw, if y'all are looking for to a greater extent than String based coding problems, y'all tin either cheque here, or y'all tin purchase Cracking the Coding Interview book, which is a collection of to a greater extent than than 190 programming questions in addition to solutions from tech giants similar Amazon, Google, Facebook, in addition to Microsoft. It also includes questions from service based companies similar Infosys, TCS, in addition to Cognizant.
Solution 1 - Counting discussion using String.split() method
In this solution, nosotros volition work the split() method of java.lang.String cast to count the pose out of words inwards a given sentence. This solution uses the regular human face "\\s+" to divide the String on whitespace. The divide method returns an array, the length of array is your pose out of words inwards given String.
If y'all are novel to regular human face inwards Java, the \s is a grapheme cast to honor infinite including tabs, since \ needs to endure escaped inwards Java, it becomes \\s in addition to because in that place could endure multiple spaces betwixt words nosotros made this regular human face greedy yesteryear adding +, thence \\s+ volition let on i to a greater extent than infinite in addition to divide the String accordingly. See Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn to a greater extent than most the split() method of String class. This is also the simplest agency to count the pose out of discussion inwards a given sentence.
Solution 2 - Counting discussion inwards String using StringTokenizer
Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set, which is " \t\n\r\f": the infinite character, the tab character, the newline character, the carriage-return character, in addition to the form-feed character. Delimiter characters themselves volition non endure treated equally tokens
You tin regard that nosotros accept non given whatsoever explicit delimiter to StringTokenizer, it uses the default fix of delimiter which is plenty to let on whatsoever whitespace in addition to since words are separated yesteryear whitespace, the pose out of tokens is truly equal to the number of words inwards given String. See Java How to Program yesteryear Dietel for to a greater extent than information on StringTokenizer cast inwards Java.
Solution 3 - Counting discussion inwards String without using library method
Here is the code to count a pose out of words inwards a given String without using whatsoever library or utility method. This is what y'all may accept written inwards C or C++. It iterates through String array in addition to checks every character. It assume that a discussion start alongside a missive of the alphabet in addition to ends alongside something which is non a letter. Once it encounters a non-letter it increments the counter in addition to starts searching i time to a greater extent than from the adjacent postion.
That's all most how to count a pose out of words inwards Java String. I accept shown y'all 3 ways to solve this problem, commencement yesteryear using split() method in addition to regular expression, minute yesteryear using StringTokenizer cast in addition to tertiary without using whatsoever library method to solve this job take e.g. divide or StringTokenizer. Depending upon your need, y'all tin work whatsoever of these methods. Interviewer unremarkably asks y'all produce it on the tertiary way, so endure cook for that. You tin also solve to a greater extent than String problems given on Cracking the Code Interview mass to gain to a greater extent than exercise in addition to confidence.
Other String based coding problems y'all may similar to solve
References
java.lang.String documentation
In this article, I'll portion all 3 ways to solve this job i.e. commencement yesteryear using String's split() method in addition to regular expression, minute yesteryear using StringTokenizer in addition to tertiary without using whatsoever library method similar above. The tertiary i is the most interesting in addition to really hard to write a consummate solution treatment all exceptional characters e.g. non-printable ASCII characters. for our purpose, nosotros assume that infinite grapheme includes tab, infinite or novel business in addition to anything which is considered equally a missive of the alphabet yesteryear Character.isLetter() is considered equally a word.
Btw, if y'all are looking for to a greater extent than String based coding problems, y'all tin either cheque here, or y'all tin purchase Cracking the Coding Interview book, which is a collection of to a greater extent than than 190 programming questions in addition to solutions from tech giants similar Amazon, Google, Facebook, in addition to Microsoft. It also includes questions from service based companies similar Infosys, TCS, in addition to Cognizant.
Solution 1 - Counting discussion using String.split() method
In this solution, nosotros volition work the split() method of java.lang.String cast to count the pose out of words inwards a given sentence. This solution uses the regular human face "\\s+" to divide the String on whitespace. The divide method returns an array, the length of array is your pose out of words inwards given String.
public static int countWordsUsingSplit(String input) { if (input == null || input.isEmpty()) { return 0; } String[] words = input.split("\\s+"); return words.length; }
If y'all are novel to regular human face inwards Java, the \s is a grapheme cast to honor infinite including tabs, since \ needs to endure escaped inwards Java, it becomes \\s in addition to because in that place could endure multiple spaces betwixt words nosotros made this regular human face greedy yesteryear adding +, thence \\s+ volition let on i to a greater extent than infinite in addition to divide the String accordingly. See Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn to a greater extent than most the split() method of String class. This is also the simplest agency to count the pose out of discussion inwards a given sentence.
Solution 2 - Counting discussion inwards String using StringTokenizer
Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set, which is " \t\n\r\f": the infinite character, the tab character, the newline character, the carriage-return character, in addition to the form-feed character. Delimiter characters themselves volition non endure treated equally tokens
public static int countWordsUsingStringTokenizer(String sentence) { if (sentence == null || sentence.isEmpty()) { return 0; } StringTokenizer tokens = new StringTokenizer(sentence); return tokens.countTokens(); }
You tin regard that nosotros accept non given whatsoever explicit delimiter to StringTokenizer, it uses the default fix of delimiter which is plenty to let on whatsoever whitespace in addition to since words are separated yesteryear whitespace, the pose out of tokens is truly equal to the number of words inwards given String. See Java How to Program yesteryear Dietel for to a greater extent than information on StringTokenizer cast inwards Java.
Solution 3 - Counting discussion inwards String without using library method
Here is the code to count a pose out of words inwards a given String without using whatsoever library or utility method. This is what y'all may accept written inwards C or C++. It iterates through String array in addition to checks every character. It assume that a discussion start alongside a missive of the alphabet in addition to ends alongside something which is non a letter. Once it encounters a non-letter it increments the counter in addition to starts searching i time to a greater extent than from the adjacent postion.
public static int count(String word) { if (word == null || word.isEmpty()) { return 0; } int wordCount = 0; boolean isWord = false; int endOfLine = word.length() - 1; char[] characters = word.toCharArray(); for (int i = 0; i < characters.length; i++) { // if the char is a letter, discussion = true. if (Character.isLetter(characters[i]) && i != endOfLine) { isWord = true; // if char isn't a missive of the alphabet in addition to in that place accept been letters before, // counter goes up. } else if (!Character.isLetter(characters[i]) && isWord) { wordCount++; isWord = false; // final discussion of String; if it doesn't cease alongside a non letter, it // wouldn't count without this. } else if (Character.isLetter(characters[i]) && i == endOfLine) { wordCount++; } } return wordCount; }
If y'all desire to exercise only about to a greater extent than of this type of question, y'all tin also cheque the Cracking the Coding Interview, i of the biggest collection of Programming Questions, in addition to Solutions from technical interviews.
Java Program to count a pose out of words inwards String
Here is our consummate Java plan to count a pose out of words inwards a given String sentence. It demonstrates all 3 examples nosotros accept seen so far e.g. using String.split() method, using StringTokenizer in addition to writing your ain method to count the pose out of words without using whatsoever tertiary political party library e.g. Google Guava or Apache Commons.import java.util.StringTokenizer; /* * Java Program to count pose out of words inwards String. * This plan solves the job inwards 3 ways, * yesteryear using String.split(), StringTokenizer, in addition to * without whatsoever of them yesteryear only writing ain logic */ public class Main { public static void main(String[] args) { String[] testdata = { "", null, "One", "O", "Java in addition to C++", "a b c", "YouAre,best" }; for (String input : testdata) { System.out.printf( "Number of words inwards stirng '%s' using split() is : %d %n", input, countWordsUsingSplit(input)); System.out.printf( "Number of words inwards stirng '%s' using StringTokenizer is : %d %n", input, countWordsUsingStringTokenizer(input)); System.out.printf("Number of words inwards stirng '%s' is : %d %n", input, count(input)); } } /** * Count pose out of words inwards given String using split() in addition to regular human face * * @param input * @return pose out of words */ public static int countWordsUsingSplit(String input) { if (input == null || input.isEmpty()) { return 0; } String[] words = input.split("\\s+"); return words.length; } /** * Count pose out of words inwards given String using StirngTokenizer * * @param judgement * @return count of words */ public static int countWordsUsingStringTokenizer(String sentence) { if (sentence == null || sentence.isEmpty()) { return 0; } StringTokenizer tokens = new StringTokenizer(sentence); return tokens.countTokens(); } /** * Count pose out of words inwards given String without split() or whatsoever other utility * method * * @param discussion * @return pose out of words separated yesteryear infinite */ public static int count(String word) { if (word == null || word.isEmpty()) { return 0; } int wordCount = 0; boolean isWord = false; int endOfLine = word.length() - 1; char[] characters = word.toCharArray(); for (int i = 0; i < characters.length; i++) { // if the char is a letter, discussion = true. if (Character.isLetter(characters[i]) && i != endOfLine) { isWord = true; // if char isn't a missive of the alphabet in addition to in that place accept been letters before, // counter goes up. } else if (!Character.isLetter(characters[i]) && isWord) { wordCount++; isWord = false; // final discussion of String; if it doesn't cease alongside a non letter, it // wouldn't count without this. } else if (Character.isLetter(characters[i]) && i == endOfLine) { wordCount++; } } return wordCount; } } Output Number of words in string '' using split() is : 0 Number of words in string '' using StringTokenizer is : 0 Number of words in string '' is : 0 Number of words in string 'null' using split() is : 0 Number of words in string 'null' using StringTokenizer is : 0 Number of words in string 'null' is : 0 Number of words in string 'One' using split() is : 1 Number of words in string 'One' using StringTokenizer is : 1 Number of words in string 'One' is : 1 Number of words in string 'O' using split() is : 1 Number of words in string 'O' using StringTokenizer is : 1 Number of words in string 'O' is : 1 Number of words in string 'Java in addition to C++' using split() is : 3 Number of words in string 'Java in addition to C++' using StringTokenizer is : 3 Number of words in string 'Java in addition to C++' is : 3 Number of words in string 'a b c' using split() is : 3 Number of words in string 'a b c' using StringTokenizer is : 3 Number of words in string 'a b c' is : 3 Number of words in string 'YouAre,best' using split() is : 1 Number of words in string 'YouAre,best' using StringTokenizer is : 1 Number of words in string 'YouAre,best' is : 2
That's all most how to count a pose out of words inwards Java String. I accept shown y'all 3 ways to solve this problem, commencement yesteryear using split() method in addition to regular expression, minute yesteryear using StringTokenizer cast in addition to tertiary without using whatsoever library method to solve this job take e.g. divide or StringTokenizer. Depending upon your need, y'all tin work whatsoever of these methods. Interviewer unremarkably asks y'all produce it on the tertiary way, so endure cook for that. You tin also solve to a greater extent than String problems given on Cracking the Code Interview mass to gain to a greater extent than exercise in addition to confidence.
Other String based coding problems y'all may similar to solve
- How to contrary a String inwards house inwards Java? (solution)
- How to let on all permutations of a given String inwards Java? (solution)
- How to cheque if ii given Strings are Anagram inwards Java? (solution)
- How to cheque if a String contains duplicate characters inwards Java? (solution)
- How to let on the highest occurring discussion from a given file inwards Java? (solution)
- How to count vowels in addition to consonants inwards given String inwards Java? (solution)
- How to cheque if given String is palindrome or non inwards Java? (solution)
- How to take duplicate characters from String inwards Java? (solution)
- How to contrary words inwards a given String inwards Java? (solution)
References
java.lang.String documentation


0 Response to "3 ways to count words inward Java String"
Posting Komentar