Extract words among spaces

joboc
1,567 views
undefined

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
#include <algorithm>
#include <iostream>
#include <vector>
template <typename OutputIterator>
void extractWords(std::string const& s, OutputIterator out)
{
static auto const isSpace = [](char letter){ return letter == ' '; };
auto const beginWord = std::find_if_not(begin(s), end(s), isSpace);
auto const endWord = std::find_if(beginWord, end(s), isSpace);
if (beginWord != endWord)
{
*out = std::string(beginWord, endWord);
++out;
}
}
auto extractWordsVector(std::string const& s)
{
std::vector<std::string> results;
extractWords(s, back_inserter(results));
return results;
}
bool testsPassed()
{
bool passed = true;
passed = passed && (extractWordsVector("word1 word2 ") == std::vector<std::string>{"word1", "word2"});
passed = passed && (extractWordsVector(" word1 word2 ") == std::vector<std::string>{"word1", "word2"});
passed = passed && (extractWordsVector(" word1 word2") == std::vector<std::string>{"word1", "word2"});
passed = passed && (extractWordsVector(" ") == std::vector<std::string>{});
passed = passed && (extractWordsVector("") == std::vector<std::string>{});
return passed;
}
int main()
{
std::cout << (testsPassed() ? "TESTS PASSED" : "TESTS FAILED") << '\n';
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content