How to Find Substring in String in C++

Jinku Hu Mar 11, 2025 C++ C++ String
  1. Using the find() Method
  2. Using the substr() Method
  3. Using Regular Expressions
  4. Conclusion
  5. FAQ
How to Find Substring in String in C++

In the world of programming, working with strings is a common task, especially in languages like C++. One of the most frequent operations is checking if a string contains a specific substring. This can be useful for various applications, from data validation to searching within text.

In this article, we will explore multiple methods to find a substring within a string in C++. Whether you’re a beginner or an experienced developer, understanding these techniques will enhance your string manipulation skills. Let’s dive into the various methods you can use to check for substrings in C++.

Using the find() Method

One of the most straightforward ways to check if a string contains a substring in C++ is by using the find() method. This method is a member of the std::string class and returns the position of the first occurrence of the specified substring. If the substring is not found, it returns std::string::npos.

Here’s a simple example:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, welcome to the world of C++ programming!";
    std::string substr = "welcome";

    if (str.find(substr) != std::string::npos) {
        std::cout << "Substring found!" << std::endl;
    } else {
        std::cout << "Substring not found." << std::endl;
    }

    return 0;
}

Output:

Substring found!

In this code, we first include the necessary headers and define our main function. We create a string str and a substring substr. The find() method checks if substr exists in str. If it does, it outputs “Substring found!” Otherwise, it outputs “Substring not found.” This method is efficient and easy to implement, making it a popular choice among developers.

Using the substr() Method

Another effective method to find a substring in C++ is by utilizing the substr() method in conjunction with a loop. This method allows you to extract parts of a string, making it possible to iterate through the main string and check for matches.

Here’s how this can be done:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, welcome to the world of C++ programming!";
    std::string substr = "world";
    bool found = false;

    for (size_t i = 0; i <= str.length() - substr.length(); ++i) {
        if (str.substr(i, substr.length()) == substr) {
            found = true;
            break;
        }
    }

    if (found) {
        std::cout << "Substring found!" << std::endl;
    } else {
        std::cout << "Substring not found." << std::endl;
    }

    return 0;
}

Output:

Substring found!

In this example, we loop through the main string str and use substr(i, substr.length()) to extract a portion of str starting from index i and of the same length as substr. We compare this extracted substring to substr. If they match, we set found to true and break out of the loop. Finally, we check the found variable to determine if the substring exists. This method is slightly more complex but provides a deeper understanding of string manipulation.

Using Regular Expressions

For more advanced substring searching, you can use regular expressions in C++. The <regex> library provides powerful tools for pattern matching, making it easier to find substrings that match specific patterns.

Here’s a quick example of how to use regular expressions:

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string str = "Hello, welcome to the world of C++ programming!";
    std::string substr = "C\\+\\+";

    std::regex pattern(substr);

    if (std::regex_search(str, pattern)) {
        std::cout << "Substring found!" << std::endl;
    } else {
        std::cout << "Substring not found." << std::endl;
    }

    return 0;
}

Output:

Substring found!

In this code, we include the <regex> library and create a regular expression pattern to match the substring. The std::regex_search() function checks if the pattern exists within the string. This method is particularly useful when you need to match substrings based on complex criteria, such as wildcards or specific character classes.

Conclusion

Finding a substring in a string in C++ can be accomplished through various methods, each with its own advantages. Whether you choose to use the find() method for simplicity, the substr() method for flexibility, or regular expressions for advanced pattern matching, understanding these techniques will enhance your programming toolkit. By mastering these methods, you can efficiently handle string manipulations in your C++ projects, making your code more robust and versatile.

FAQ

  1. What is the fastest way to find a substring in C++?
    The fastest way is to use the find() method, as it is optimized for performance.

  2. Can I find a substring in a case-insensitive manner?
    Yes, you can convert both the string and substring to the same case (either lower or upper) before using the find() method.

  1. What should I do if I need to find multiple occurrences of a substring?
    You can use a loop with the find() method, updating the starting index each time you find an occurrence.

  2. Are there any limitations to using regular expressions for substring searches?
    Regular expressions can be slower than other methods, especially for simple substring searches, due to their complexity.

  3. How can I check if a string starts with a specific substring in C++?
    You can use the find() method to check if the substring is at index 0 of the string.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C++ String