Programs & Examples
std::string · Study material
Reverse the order of words in a sentence
Reading with >> from an istringstream splits on any amount of whitespace; std::reverse flips the word list and a loop joins it back.
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::string sentence = "practice makes a programmer perfect";
std::istringstream in(sentence);
std::vector<std::string> words;
for (std::string w; in >> w; ) words.push_back(w);
std::reverse(words.begin(), words.end());
std::string out;
for (const auto& w : words) out += (out.empty() ? "" : " ") + w;
std::cout << out << '\n';
return 0;
}
perfect programmer a makes practice
Run-length compression (aaabcc → a3bc2)
Find the end of each run of equal characters, write the character and – if the run is longer than one – its length.
#include <iostream>
#include <string>
std::string compress(const std::string& s) {
std::string out;
for (std::size_t i = 0; i < s.size(); ) {
std::size_t j = i;
while (j < s.size() && s[j] == s[i]) ++j;
out += s[i];
if (j - i > 1) out += std::to_string(j - i);
i = j;
}
return out;
}
int main() {
for (std::string s : {"aaabccdddd", "abc", "zzzzzzzzzzzz"})
std::cout << s << " -> " << compress(s) << '\n';
return 0;
}
aaabccdddd -> a3bc2d4 abc -> abc zzzzzzzzzzzz -> z12
Split and join a CSV line
The split and join helpers from the introduction are a reusable pair: getline with a delimiter splits, a loop with += joins.