Meta Interview Question

Figure out how many words are in a string

Interview Answers

Anonymous

Apr 4, 2017

Usually this kind of questions they give you a string composed by words WITHOUT spaces and a method to check if a given string is a real word or not. Just to counting the number of spaces is too easy. For instance: "thisisarealsentence" -> "this is a real sentence" (5 words)

2

Anonymous

Dec 14, 2016

Robert, solution is totally wrong) you are counting spaces not the words)

Anonymous

Dec 19, 2016

He's not really wrong. In the case of an empty string the length of the string will be 0. The moment you add a character we assume it's a word. With this in mind there are a couple of assumptions to be made: 1.) assuming you're not asking to check if the word is actually an {insert language here} word. 2.) we're assuming there is an equal amount of spaces between each word. 3.) there is no extra space at the end of the sentence. The moment you begin counting pass 1 you know that there will be n + 1 words where n is the numbers of spaces. If these assumptions were made by Robert, he isn't exactly wrong to count spaces.

Anonymous

Feb 9, 2017

In java, I would use the split method, is that not allowed? And store into a string array, then get size of array.

Anonymous

Nov 30, 2016

- (int)numberOfWordsInString:(NSString *)phrase { int numberOfWords = 0; for(int i = 0; i < phrase.stringLength.count; i++) { char *currentLetter = phrase[i]; if ([char isEqualToString:@" "]){ numberOfWords++; } } return numberOfWords; } *this is not a real programming language this is just how i would do it in my head