Extract words among spaces
joboc
17.5K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#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';
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content