This is an interview question from http://www.glassdoor.com/Interview/Indeed-Software-Engineer-Interview-Questions-EI_IE100561.0,6_KO7,24.htm , specifically, the problem
"The asked me a method that took in a string and return words up to the max length. There could be any amount of spaces which made it a little tricky "
Here is my solution(with test case)
public class MaxLength {
public static void main(String[] args) {
List<String> allWords = maxWords("Jasmine has no love for chris", 2);
for(String word: allWords){
System.out.println(word);
}
}
public static List<String> maxWords(String sentence, int length) {
String[] words = sentence.trim().split("\\s+");
List<String> list = new ArrayList<String>();
for(String word: words) {
if(word.length() <= length) {
list.add(word);
}
}
return list;
}
The test ran fine and i got my expected output - no. However during an actual interview, I think the interviewer doesn't expect you to know this regular expression off the top of your head (I didn't had to find it from How do I split a string with any whitespace chars as delimiters?) Is there another approach to this problem without using regular expressions?