Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::basic_string::find — substring search and required separators

Find the first match at or after a starting position, check for `npos`, and use an explicit pattern length when a buffer may contain embedded nulls.

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

Syntax

// ISO C++23; member declarations of std::basic_string<CharT, Traits, Allocator> in <string>
constexpr size_type find(const basic_string& str, size_type pos = 0) const noexcept;
constexpr size_type find(const CharT* s, size_type pos, size_type count) const;
constexpr size_type find(const CharT* s, size_type pos = 0) const;
constexpr size_type find(CharT ch, size_type pos = 0) const noexcept;
template<class T>
constexpr size_type find(const T& t, size_type pos = 0) const
    noexcept(std::is_nothrow_convertible_v<const T&, std::basic_string_view<CharT, Traits>>);
// The template participates only if const T& is implicitly convertible to
// std::basic_string_view<CharT, Traits> but not to const CharT*.

std::basic_string::find is a const member function from <string>, also available on std::string. It returns a zero-based size_type index: the earliest position at or after pos (default 0) where the whole pattern fits and matches. It compares elements using Traits::eq. For UTF-8 stored in std::string, the index counts bytes, not user-visible characters.

No match returns npos, the largest size_type value, not an exception. An empty pattern matches at pos exactly when pos <= size(); a nonempty pattern cannot match when pos >= size(). For a required separator, check for npos before indexing, slicing, or doing offset arithmetic. Index 0 is a successful result.

find(ch, pos) searches for one CharT; find(str, pos) uses the full length of a basic_string. find(p, pos) requires a null-terminated sequence: Traits::length stops at the first null. find(p, pos, count) uses exactly count pattern elements, including embedded nulls. The second argument is the start position, not a length, and count does not bound the string being searched. An invalid pointer range causes undefined behavior, so check that count does not exceed the number of readable elements starting at p.

Since C++17, the template overload accepts const T& if it is implicitly convertible to std::basic_string_view<CharT, Traits> but not to const CharT*. A view retains its length but does not own the storage. Keep the data behind a view or pointer valid throughout the call. For a std::vector<char> buffer, pair data() with size(); do not assume a trailing null.

All overloads are constexpr since C++20. In C++23 the basic_string and CharT overloads are noexcept, the pointer overloads are not declared noexcept, and the template is noexcept only if conversion to the view is non-throwing. Implementation support may vary.

Examples

#include <iostream>
#include <string>
#include <string_view>
#include <vector>

int main() {
    const std::string record{"A:B:\0=C", 7};
    const std::vector<char> separator{':', '\0', '='};

    std::cout << "C string: " << record.find(separator.data()) << '\n';

    const auto split = record.find(separator.data(), 0, separator.size());
    if (split == std::string::npos) {
        std::cout << "Missing required separator\n";
        return 1;
    }
    std::cout << "Counted separator: " << split << '\n';

    const std::string_view marker{separator.data(), separator.size()};
    const auto start = split + 1;
    const auto next = record.find(marker, start);
    std::cout << "From index " << start << ": ";
    if (next == std::string::npos) {
        std::cout << "not found\n";
    } else {
        std::cout << next << '\n';
    }
}

Result

C string: 1
Counted separator: 3
From index 4: not found

The pointer-only call looks for `:` and returns `1`. The counted call finds the full required separator `:\0=` at index `3`. Searching for the same pattern as a view from index `4` returns `npos`.

Related lessons

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

Sources