C++ std::string_view::substr and find
std::string_view refers to existing character storage. find locates a separator and substr returns a view of part of the same storage.
A simple example
std::string_view::substr and find
- Start with "a=b"
- Do this Split at the first equals sign
- Result Left a, right b
Syntax
setting.find('=') / setting.substr(position, length)
Run this example in C++
Save the program as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
Split a setting without copying its text
A configuration line separates a key from its value with punctuation. Split only at the first intended boundary because the value itself may contain the same separator later on.
#include <iostream>
#include <string_view>
int main() {
for (std::string_view setting : {"mode=", "broken"}) {
auto pos = setting.find('=');
if (pos == std::string_view::npos) {
std::cout << "invalid\n";
continue;
}
std::cout << setting.substr(0, pos) << " -> [" << setting.substr(pos + 1) << "]\n";
}
return 0;
}
mode -> [] invalid
An empty value is valid here. Test for npos before computing the position after the separator, and keep the underlying string alive while using either view.
C++ working draft for std::string_view::substr and find
Read a parcel sorting code
The depot scans a parcel marked NC-17. The printer needs the two-letter prefix that comes before the separator. Which letters should it print?
Read a music-room label
A school labels its second practice room MU-24. The printer needs the two-letter prefix that comes before the separator. Which letters should it print?