Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::string::find — first match and npos

Find the index of a character or substring and compare it with `std::string::npos` before using it as an index or copying or changing the text.

Version: ISO C++23; implementation support may vary

Syntax

// C++23 member declarations, with types written for std::string (<string>).
// The template participates only if const T& is implicitly convertible to
// std::string_view but not to const char*.
constexpr size_type find(char ch, size_type pos = 0) const noexcept;
constexpr size_type find(const std::string& needle, size_type pos = 0) const noexcept;
constexpr size_type find(const char* needle, size_type pos = 0) const;
constexpr size_type find(const char* needle, size_type pos, size_type count) const;
template<class T>
constexpr size_type find(const T& needle, size_type pos = 0) const
    noexcept(std::is_nothrow_convertible_v<const T&, std::string_view>);
static constexpr size_type npos = size_type(-1);

std::string::find is a const member of std::string from <string>. It returns the lowest zero-based match index at or after pos (default 0). The entire search pattern must fit. An empty pattern matches at pos if pos <= s.size(); a nonempty pattern cannot match if pos >= s.size(). Matching is case-sensitive, and indices count char elements, not Unicode code points.

The result is a std::string::size_type. A miss does not throw: it returns std::string::npos, the largest value of that unsigned type. Test i != std::string::npos before indexing or doing index arithmetic. if (i) is false for a valid match at 0 and true for npos. The result is a number, not an iterator or a view, and it may no longer identify the same match after the text changes.

Use s.find('!') for one character. For a substring, pass a std::string, a std::string_view, or a valid null-terminated string, as in s.find("ab"). In s.find(ptr, pos, count), count is the pattern length, not a limit on the search; the pattern may include \0. Any pointer or view supplied must refer to valid data throughout the call. An invalid range does not produce npos: it causes undefined behavior.

The char and std::string overloads are noexcept; the pointer overloads are not declared noexcept. The template overload, available since C++17, accepts types implicitly convertible to std::string_view but not to const char*; its noexcept depends on the conversion to the view. All overloads are constexpr since C++20. If you only need a yes/no answer and no starting position, s.contains('!') is a C++23 alternative where supported by the library.

When s is already a std::string, test s.find('!') != std::string::npos before making a working copy or modifying the text. The search itself neither copies nor changes s. This check rejects !; it does not replace other validation rules.

Examples

#include <iostream>
#include <string>

void process(const std::string& input) {
    const auto bad = input.find('!');
    if (bad != std::string::npos) {
        std::cout << "rejected at " << bad << '\n';
        return;
    }

    auto result = input;
    result += '.';
    std::cout << "accepted: " << result << '\n';
}

int main() {
    const std::string invalid = "!abc";
    const std::string valid = "abc";
    process(invalid);
    process(valid);
}

Result

rejected at 0
accepted: abc.

In `!abc`, the `!` is at index `0`, so the function returns before making a copy. For `abc`, the search misses, and only then does the function make a copy and append a period to it.

Related lessons

  • C++ · Lesson 15 · Advanced · Version: 3

Sources