Library contents

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

  1. Start with "a=b"
  2. Do this Split at the first equals sign
  3. Result Left a, right b
The equals sign marks the boundary between the two fields.

Syntax

C++ 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.

From the programfor (std::string_view setting : {"mode=", "broken"}) {
First output linemode -> []
lesson.cpp
#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;
}
Output
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

Advertisements

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?

GivenNC-17
Worked resultNC

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?

GivenMU-24
Worked resultMU