0Pricing
C++ Academy · Lesson

String Algorithms

Search and split efficiently.

Searching with find

find returns the index of a substring or npos if absent, working directly on a view without copying.

#include <iostream>
#include <string_view>
int main() {
    std::string_view sv = "key=value";
    auto pos = sv.find('=');
    std::cout << pos << "\n"; // 3
}

Checking npos

Always compare a search result against std::string_view::npos before using it as an index.

#include <iostream>
#include <string_view>
int main() {
    std::string_view sv = "abc";
    if (sv.find('z') == std::string_view::npos)
        std::cout << "not found\n";
}

All lessons in this course

  1. Why string_view
  2. Creating Views
  3. Pitfalls and Lifetimes
  4. String Algorithms
← Back to C++ Academy