0
0
CppHow-ToBeginner · 3 min read

How to Find Substring in C++: Simple Guide with Examples

In C++, you can find a substring inside a string using the std::string::find method. It returns the position of the first occurrence of the substring or std::string::npos if not found.
📐

Syntax

The basic syntax to find a substring in C++ is:

size_t pos = str.find(substring);

Here:

  • str is the main string you want to search in.
  • substring is the string you want to find.
  • pos will hold the index where substring starts in str.
  • If substring is not found, pos will be std::string::npos, a special value.
cpp
size_t pos = str.find(substring);
💻

Example

This example shows how to find a substring and check if it exists in the main string.

cpp
#include <iostream>
#include <string>

int main() {
    std::string text = "Hello, welcome to C++ programming!";
    std::string word = "welcome";

    size_t position = text.find(word);

    if (position != std::string::npos) {
        std::cout << "Found '" << word << "' at position " << position << ".\n";
    } else {
        std::cout << "Substring not found.\n";
    }

    return 0;
}
Output
Found 'welcome' at position 7.
⚠️

Common Pitfalls

Common mistakes when finding substrings in C++ include:

  • Not checking if the result is std::string::npos before using the position.
  • Confusing npos with -1. npos is an unsigned value and should be compared using != std::string::npos.
  • Using find on empty strings or searching for empty substrings without understanding the behavior.
cpp
#include <iostream>
#include <string>

int main() {
    std::string text = "example";
    std::string search = "z";

    // Wrong: Not checking for npos
    size_t pos = text.find(search);
    // Using pos directly without check can cause bugs

    if (pos != std::string::npos) {
        std::cout << "Found at " << pos << "\n";
    } else {
        std::cout << "Not found" << std::endl;
    }

    return 0;
}
Output
Not found
📊

Quick Reference

Summary tips for using std::string::find:

  • Returns the index of the first match or std::string::npos if not found.
  • Use if (pos != std::string::npos) to check if found.
  • Can specify a starting position: str.find(substring, start_pos).
  • Works with std::string and C-style strings.

Key Takeaways

Use std::string::find to locate a substring's position in a string.
Always check if the result is std::string::npos before using the position.
The find method returns the first occurrence index or npos if not found.
You can specify a starting index to search from in the find method.
Avoid using the position without verifying it is not npos to prevent bugs.