C++: Strings – code examples
Counting words
Strings#map#istringstream#text#counting
Use case: Text analysis, e.g. most frequent words in a document or log file.
#include <iostream>
#include <map>
#include <sstream>
#include <string>
int main() {
std::istringstream text("this is a test this is good");
std::map<std::string, int> zaehler;
std::string wort;
while (text >> wort) ++zaehler[wort];
for (const auto& [w, n] : zaehler) std::cout << w << ": " << n << '\n';
}>> reads word by word (whitespace as separator). zaehler[wort] creates missing keys with 0 – exactly what we want here, so ++ is enough.
Splitting a string at a delimiter
Strings#split#getline#stringstream#csv
Use case: Split CSV lines or paths into parts.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> teile(const std::string& s, char trenner) {
std::vector<std::string> ergebnis;
std::istringstream in(s);
std::string teil;
while (std::getline(in, teil, trenner)) ergebnis.push_back(teil);
return ergebnis;
}
int main() {
for (const auto& t : teile("a,b,c", ',')) std::cout << t << '\n';
}std::getline with a third argument reads up to the delimiter. The standard library has no split; since C++20 it can also be done with std::views::split.
std::format (C++20)
Strings#format#string#c++20
Use case: Format tables, logs and output with width and decimal places.
#include <format>
#include <iostream>
int main() {
std::cout << std::format("{:>8.2f}|{:<5}|{:03}\n", 3.14159, "ab", 7);
std::cout << std::format("{} has {} points\n", "Ada", 42);
}Placeholders {} with format specifications as in Python. Output: 3.14|ab |007 and Ada has 42 points. Requires GCC 13+, Clang 17+ or MSVC 2019 16.10+.