I am trying to write some code which retrieves the first 10 words of a string.
The best algorithm I can imagine is to split the string by space and take the first 10 elements. However, this is not bery efficient as the string could be very long.
Is there any better algorithm in Java that can achieve this?
Many thanks.
You can use
String.split(String regex,int limit)with a specific limit – don’t invoke the regex rule more then 11 times.It will create a
String[]object, with 10 first elements are seperate words, and the last element contain words where the rule was not checked on yet [so it will not split the rest of the string]