Tutorial

How to use the string find() in C++

Published on August 3, 2022
Default avatar

By Vijaykrishna Ram

How to use the string find() in C++

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this article, we’ll take a look at how we can use String find() in C++.

If we want to check whether a string contains another string, the std::string.find() method is very useful. Let’s understand how we can use this method, with some examples!


Syntax of String find() in C++

This method belongs to the C++ string class (std::string). And therefore, we must include the header file <string>,

We must invoke this on a string object, using another string as an argument.

The find() method will then check if the given string lies in our string. It will return the size of the sub-string including the '\0' terminating character (as size_t). But if the string does not lie in our original string, it will return 0.

With that, the function is defined like this:

size_t find(const std::string& my_string, size_t pos = 0);

There is one more parameter, pos, which defines the starting position to search from.

By default, it is 0, so unless you explicitly specify the start position, searching will happen from the start of the string.

Also notice that the string is passed by const reference.

As we’re not modifying any of the strings, it makes more sense to not waste time creating a temporary string, as we can directly work with references.

NOTE: From C++20 onward, many of the standard library methods are now constexpr compatible, so they are executed during compile time itself. You can read more about constexpr intricacies online.

There are a couple of function overloads, most of which I will be skipping since you can look at this page for more information. Instead, we’ll focus on one particular overload, that involves the substring length.

size_t find( const Char* s, size_type pos, size_type count )

This particular overload checks if the substring lies within our string, but it also has a limit for the substring length. This will match until count characters.

But this cannot be used for std::string. Notice that const Char* in the prototype. So, we can use this only for C-style strings.

For example, if we pass the substring “Hell” to “Hello” to this function.

std::cout << "Hello".find("Hell", 0, 3) << std::endl;

This will only match 3 characters, from the start of “Hello”. So, we’ll get only 4 bytes as the output, as opposed to 5.

Let’s now look at some examples to understand what we’ve learnt.


Using string.find() in C++

Let’s look at the default call, when pos=0. We’ll simply search for the whole substring, from the start of the string.

#include <iostream>
#include <string>

int main() {
    // Create our string
    std::string my_str("Hello from JournalDev");
    // Target string to search for
    std::string target_string("JournalDev");

    std::cout << "Is " << target_string << " a substring of " << my_str << " ?\n";
    size_t substring_length = my_str.find(target_string);
    if (substring_length == 0)
        std::cout << "No\n";
    else
        std::cout << "Length of matched substring = " << substring_length << std::endl;

    return 0;
}

Output:

Is JournalDev a substring of Hello from JournalDev ?
Length of matched substring = 11

As you can see, the substring is indeed there inside our original string!

Let’s now search the same substring from a specific position on the string.

#include <iostream>
#include <string>

int main() {
    // Create our string
    std::string my_str("Hello from JournalDev");
    // Target string to search for
    std::string target_string("JournalDev");

    std::cout << "Is " << target_string << " a substring of " << my_str << " ?\n";
    size_t substring_length = my_str.find(target_string, 12); // Start from index 12 (from my_str[12])
    if (substring_length == 0)
        std::cout << "No\n";
    else
        std::cout << "Length of matched substring = " << substring_length << std::endl;

    return 0;
}

Output

Is JournalDev a substring of Hello from JournalDev ?
Length of matched substring = 18446744073709551615

Why are we getting such a weird output? Well, since we started from index 12 on the original string, and the length of our sub-string, from this position, will go beyond the length of the original string!

We therefore go to a garbage location, after reaching the end of our string. find() goes beyond the end of the string, so keep this in mind.

We’ll therefore fix this dangerous state, by checking whether we’ve reached the end of the string.

C++ has a special variable called std::string::npos, that returns a handle to the current string that we can use to detect if we’ve reached the end of our string.

if (my_str.find(target_str) != std::string::npos) {
    // This matches! We're still within the original string
}
else {
    // Oops! Out of bounds. Print error message!
}

With this change, our code will now look like this:

#include <iostream>
#include <string>

int main() {
    // Create our string
    std::string my_str("Hello from JournalDev");
    // Target string to search for
    std::string target_string("JournalDev");

    std::cout << "Is " << target_string << " a substring of " << my_str << " ?\n";
    size_t substring_length;
    if ((substring_length = my_str.find(target_string, 12)) != std::string::npos) {
        std::cout << "Length of matched substring = " << substring_length << std::endl;
    }
    else {
        std::cout << "No\n";
    }

    return 0;
}

Output

Is JournalDev a substring of Hello from JournalDev ?
No

Now, we get our expected output, since we start from index 12!

Let’s use this check to show the other overloaded form of find(), using a count. Remember that we cannot use this form directly on C++ strings.

#include <iostream>
#include <string>

int main() {
    // Create our string
    std::string my_str("Hello from JournalDev");
    // Target string to search for
    std::string target_string("Journ_kkfffsfsfskkk");

    std::cout << "Is " << target_string << " a substring of " << my_str << " ?\n";
    size_t substring_length;
    // Use a count to match only 5 characters
    // Note that we can use this form only for const char* strings
    if ((substring_length = my_str.find("Journ_kkfffsfsfskkk", 0, 5)) != std::string::npos) {
        std::cout << "Length of matched substring = " << substring_length << std::endl;
    }
    else {
        std::cout << "No\n";
    }

    return 0;
}

Output

Is Journ_kkfffsfsfskkk a substring of Hello from JournalDev ?
Length of matched substring = 11

Observe that our we’ve changed our target string. Here, although only the first 5 characters will get matched, that is enough for find(), since we’ve put a counter limit of 5!

So, it will simply ignore the rest of the target sub-string, and continue matching our original string until the end of the string!

That’s why we still get 11, since that’s where the substring match is found.


Conclusion

Hopefully, with all these example, you’ve understood how you can easily start using the string.find() method in C++. If you have any doubts, do ask them in the comment section below!

Also, do have a look at some of our other articles related to C++ in our tutorials section!


References


Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Vijaykrishna Ram

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel