C++ — Parsing text with string_view
A C++ string_view refers to existing characters. Find the first separator and take views of the two parts while the original characters are still available.
A simple example
Split one line of text
- Start with "a=b"
- Do this Separate at =
- Result b
#include <iostream>
#include <string_view>
int main() {
std::string_view text = "a=b";
std::cout << text.substr(text.find('=') + 1) << '\n';
}
b
Split one setting into a key and a value
A string_view refers to existing characters. substr creates another view. Keeping the original string literal alive makes both views valid. The example trims ASCII whitespace.
A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.
Run the example
C++17. Run these commands from the directory containing the example. Use a Unix-style shell.
c++ -std=c++17 lesson.cpp -o lesson
./lesson
#include <iostream>
#include <string_view>
std::string_view trim(std::string_view text) {
const auto first = text.find_first_not_of(" \t\r\n");
if (first == text.npos) return {};
return text.substr(first, text.find_last_not_of(" \t\r\n") - first + 1);
}
int main() {
std::string_view record = " city = Lima ";
const auto pos = record.find('=');
if (pos != record.npos) {
std::cout << trim(record.substr(0, pos)) << '='
<< trim(record.substr(pos + 1)) << '\n';
}
return 0;
}
city=Lima
The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.
Try it yourself
What should city = A=B produce?
Check your answer
The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.