You tin terminate count words inwards Java String yesteryear using the split() method of String. Influenza A virus subtype H5N1 give-and-take is aught but a non-space graphic symbol inwards String, which is separated yesteryear i or multiple spaces. By using regular aspect to discover spaces as well as split upward on them volition give you lot an array of all words inwards given String. This was the slowly means to solve this work every bit shown here, but if you lot bring been asked to write a plan to count a let on of words inwards given String inwards Java without using whatever of String utility methods similar String.split() or StringTokenizer as well as so it's a trivial flake challenging for a beginner programmer. It's genuinely i of the mutual Java coding questions as well as I bring seen it a brace of times alongside Java developer interviews of 2 to four years of experience. The interviewer pose additional constraints similar split() is non allowed, you lot tin terminate entirely utilisation basic methods similar charAt(), length(), as well as substring() along alongside loop, operators, as well as other basic programming tools.
In this article, I'll portion all 3 ways to solve this work i.e. showtime yesteryear using String's split() method as well as regular expression, minute yesteryear using StringTokenizer as well as tertiary without using whatever library method similar above. The tertiary i is the most interesting as well as real hard to write a consummate solution treatment all exceptional characters e.g. non-printable ASCII characters. for our purpose, nosotros assume that infinite graphic symbol includes tab, infinite or novel line of piece of work as well as anything which is considered every bit a missive of the alphabet yesteryear Character.isLetter() is considered every bit a word.
Btw, if you lot are looking for to a greater extent than String based coding problems, you lot tin terminate either banking concern represent here, or you lot tin terminate purchase Cracking the Coding Interview book, which is a collection of to a greater extent than than 190 programming questions as well as solutions from tech giants similar Amazon, Google, Facebook, as well as Microsoft. It also includes questions from service based companies similar Infosys, TCS, as well as Cognizant.
Solution 1 - Counting give-and-take using String.split() method
In this solution, nosotros volition utilisation the split() method of java.lang.String course of education to count the let on of words inwards a given sentence. This solution uses the regular aspect "\\s+" to split upward the String on whitespace. The split upward method returns an array, the length of array is your let on of words inwards given String.
If you lot are novel to regular aspect inwards Java, the \s is a graphic symbol course of education to honour infinite including tabs, since \ needs to last escaped inwards Java, it becomes \\s as well as because at that spot could last multiple spaces betwixt words nosotros made this regular aspect greedy yesteryear adding +, thus \\s+ volition discover i to a greater extent than infinite as well as split upward the String accordingly. See Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn to a greater extent than almost the split() method of String class. This is also the simplest means to count the let on of give-and-take inwards a given sentence.
Solution 2 - Counting give-and-take 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, as well as the form-feed character. Delimiter characters themselves volition non last treated every bit tokens
You tin terminate reckon that nosotros bring non given whatever explicit delimiter to StringTokenizer, it uses the default laid of delimiter which is plenty to discover whatever whitespace as well as since words are separated yesteryear whitespace, the let on of tokens is genuinely 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 course of education inwards Java.
Solution 3 - Counting give-and-take inwards String without using library method
Here is the code to count a let on of words inwards a given String without using whatever library or utility method. This is what you lot may bring written inwards C or C++. It iterates through String array as well as checks every character. It assume that a give-and-take start alongside a missive of the alphabet as well as ends alongside something which is non a letter. Once it encounters a non-letter it increments the counter as well as starts searching in i lawsuit to a greater extent than from the side yesteryear side postion.
That's all almost how to count a let on of words inwards Java String. I bring shown you lot 3 ways to solve this problem, showtime yesteryear using split() method as well as regular expression, minute yesteryear using StringTokenizer course of education as well as tertiary without using whatever library method to solve this work direct e.g. split upward or StringTokenizer. Depending upon your need, you lot tin terminate utilisation whatever of these methods. Interviewer unremarkably asks you lot produce it on the tertiary way, so last prepare for that. You tin terminate also solve to a greater extent than String problems given on Cracking the Code Interview majority to gain to a greater extent than practise as well as confidence.
Other String based coding problems you lot may similar to solve
Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures as well as Algorithms: Deep Dive Using Java
Algorithms as well as Data Structures - Part 1 as well as 2
In this article, I'll portion all 3 ways to solve this work i.e. showtime yesteryear using String's split() method as well as regular expression, minute yesteryear using StringTokenizer as well as tertiary without using whatever library method similar above. The tertiary i is the most interesting as well as real hard to write a consummate solution treatment all exceptional characters e.g. non-printable ASCII characters. for our purpose, nosotros assume that infinite graphic symbol includes tab, infinite or novel line of piece of work as well as anything which is considered every bit a missive of the alphabet yesteryear Character.isLetter() is considered every bit a word.
Btw, if you lot are looking for to a greater extent than String based coding problems, you lot tin terminate either banking concern represent here, or you lot tin terminate purchase Cracking the Coding Interview book, which is a collection of to a greater extent than than 190 programming questions as well as solutions from tech giants similar Amazon, Google, Facebook, as well as Microsoft. It also includes questions from service based companies similar Infosys, TCS, as well as Cognizant.
Solution 1 - Counting give-and-take using String.split() method
In this solution, nosotros volition utilisation the split() method of java.lang.String course of education to count the let on of words inwards a given sentence. This solution uses the regular aspect "\\s+" to split upward the String on whitespace. The split upward method returns an array, the length of array is your let on 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 you lot are novel to regular aspect inwards Java, the \s is a graphic symbol course of education to honour infinite including tabs, since \ needs to last escaped inwards Java, it becomes \\s as well as because at that spot could last multiple spaces betwixt words nosotros made this regular aspect greedy yesteryear adding +, thus \\s+ volition discover i to a greater extent than infinite as well as split upward the String accordingly. See Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn to a greater extent than almost the split() method of String class. This is also the simplest means to count the let on of give-and-take inwards a given sentence.
Solution 2 - Counting give-and-take 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, as well as the form-feed character. Delimiter characters themselves volition non last treated every bit tokens
public static int countWordsUsingStringTokenizer(String sentence) { if (sentence == null || sentence.isEmpty()) { return 0; } StringTokenizer tokens = new StringTokenizer(sentence); return tokens.countTokens(); }
You tin terminate reckon that nosotros bring non given whatever explicit delimiter to StringTokenizer, it uses the default laid of delimiter which is plenty to discover whatever whitespace as well as since words are separated yesteryear whitespace, the let on of tokens is genuinely 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 course of education inwards Java.
Solution 3 - Counting give-and-take inwards String without using library method
Here is the code to count a let on of words inwards a given String without using whatever library or utility method. This is what you lot may bring written inwards C or C++. It iterates through String array as well as checks every character. It assume that a give-and-take start alongside a missive of the alphabet as well as ends alongside something which is non a letter. Once it encounters a non-letter it increments the counter as well as starts searching in i lawsuit to a greater extent than from the side yesteryear side 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, give-and-take = true. if (Character.isLetter(characters[i]) && i != endOfLine) { isWord = true; // if char isn't a missive of the alphabet as well as at that spot bring been letters before, // counter goes up. } else if (!Character.isLetter(characters[i]) && isWord) { wordCount++; isWord = false; // terminal give-and-take of String; if it doesn't destination alongside a non letter, it // wouldn't count without this. } else if (Character.isLetter(characters[i]) && i == endOfLine) { wordCount++; } } return wordCount; }
If you lot desire to practise about to a greater extent than of this type of question, you lot tin terminate also banking concern represent the Cracking the Coding Interview, i of the biggest collection of Programming Questions, as well as Solutions from technical interviews.
Java Program to count a let on of words inwards String
Here is our consummate Java plan to count a let on of words inwards a given String sentence. It demonstrates all 3 examples nosotros bring seen so far e.g. using String.split() method, using StringTokenizer as well as writing your ain method to count the let on of words without using whatever tertiary political party library e.g. Google Guava or Apache Commons.import java.util.StringTokenizer; /* * Java Program to count let on of words inwards String. * This plan solves the work inwards 3 ways, * yesteryear using String.split(), StringTokenizer, as well as * without whatever of them yesteryear but writing ain logic */ public class Main { public static void main(String[] args) { String[] testdata = { "", null, "One", "O", "Java as well as 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 let on of words inwards given String using split() as well as regular aspect * * @param input * @return let on of words */ public static int countWordsUsingSplit(String input) { if (input == null || input.isEmpty()) { return 0; } String[] words = input.split("\\s+"); return words.length; } /** * Count let on 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 let on of words inwards given String without split() or whatever other utility * method * * @param give-and-take * @return let on 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, give-and-take = true. if (Character.isLetter(characters[i]) && i != endOfLine) { isWord = true; // if char isn't a missive of the alphabet as well as at that spot bring been letters before, // counter goes up. } else if (!Character.isLetter(characters[i]) && isWord) { wordCount++; isWord = false; // terminal give-and-take of String; if it doesn't destination 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 as well as C++' using split() is : 3 Number of words in string 'Java as well as C++' using StringTokenizer is : 3 Number of words in string 'Java as well as 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 almost how to count a let on of words inwards Java String. I bring shown you lot 3 ways to solve this problem, showtime yesteryear using split() method as well as regular expression, minute yesteryear using StringTokenizer course of education as well as tertiary without using whatever library method to solve this work direct e.g. split upward or StringTokenizer. Depending upon your need, you lot tin terminate utilisation whatever of these methods. Interviewer unremarkably asks you lot produce it on the tertiary way, so last prepare for that. You tin terminate also solve to a greater extent than String problems given on Cracking the Code Interview majority to gain to a greater extent than practise as well as confidence.
Other String based coding problems you lot may similar to solve
- How to opposite a String inwards house inwards Java? (solution)
- How to discover all permutations of a given String inwards Java? (solution)
- How to banking concern represent if 2 given Strings are Anagram inwards Java? (solution)
- How to banking concern represent if a String contains duplicate characters inwards Java? (solution)
- How to discover the highest occurring give-and-take from a given file inwards Java? (solution)
- How to count vowels as well as consonants inwards given String inwards Java? (solution)
- How to banking concern represent if given String is palindrome or non inwards Java? (solution)
- How to withdraw duplicate characters from String inwards Java? (solution)
- How to opposite words inwards a given String inwards Java? (solution)
Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures as well as Algorithms: Deep Dive Using Java
Algorithms as well as Data Structures - Part 1 as well as 2
No comments:
Post a Comment