c++ – How to determine the number of words of length k in a string without using loops?


Given a string where words are separated by spaces and colons. It is necessary to count the number of words less than k in length and return a container of these words. It is forbidden to use loops, only STL algorithms and containers are allowed. There is not even an idea of ​​how all this can be done. I would at least have an idea.


The solution may not be optimal, but still: Write the following recursive function: Search with std::find() in the string for a colon or a space, found – with std::substr() take all the substring before this character if its length is less than k , push_back() it into a vector. Remove this colon / space from the original line. Then call this function again if the length of the string is> 0. True, on large strings this, most likely, will not pass in time (you can try to cache the function, this greatly speeds up the process).

Scroll to Top