Library contents

C++ std::string::find

Locate the first separator or search term in a plain ASCII record.

A simple example

std::string::find

  1. Start with "aba", looking for b
  2. Do this Find the first match
  3. Result Index 1 (zero-based)
Scanning from the left reaches b after one character.
lesson.cpp
#include <iostream>
#include <string>

int main() {
    const std::string value = "aba";
    const std::string other = "b";
    std::cout << (value.find(other)) << "\n";
    return 0;
}
Output
1

Syntax

C++ syntax
value.find(other)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Locate the hyphen in a classroom code

A compound filename or route code uses punctuation to separate fields. Decide whether the first or last separator marks the desired boundary before extracting the field next to it.

From the programconst std::string value = "CS-104"
Result2
lesson.cpp
#include <iostream>
#include <string>

int main() {
    const std::string value = "CS-104";
    const std::string other = "-";
    std::cout << (value.find(other)) << "\n";
    return 0;
}
Output
2

The hyphen follows the two letters CS.

Advertisements

Find the first separator on a route

A route string contains several stops separated by the same punctuation. Find the first separator to locate the end of the starting stop before the remaining route is processed.

From the programconst std::string value = "A/B/C"
Result1
lesson.cpp
#include <iostream>
#include <string>

int main() {
    const std::string value = "A/B/C";
    const std::string other = "/";
    std::cout << (value.find(other)) << "\n";
    return 0;
}
Output
1

The first slash comes immediately after A.

Read a parcel sorting code

The depot scans a parcel marked NC-17. Find the dash in this identifier. How many characters precede the matching separator?

GivenNC-17
Worked result2

What to watch for

Check the language-specific missing-match result before slicing. Byte and character offsets may diverge for Unicode input.

Documentation for std::string::find