string::find in C++ (With Examples)

Hello! Today, we’re diving deep into a popular C++ function that helps you search within strings - string::find. We’ll start by introducing this function, explain how to use it correctly, demonstrate its behavior through some examples, and wrap up with a tutorial on creating your own simple string search function.

Searching Substrings in C++ with string::find

If you want to check whether a particular sequence of characters, or substring, exists within another string in C++, you can make use of the string::find function:

size_t string::find(const string& str, size_t pos = 0) const noexcept;
  • This function takes in a string str which you want to search for.
  • It also has an optional parameter pos which indicates where the search should begin.
  • The function returns the position of the first occurrence of the substring. If the substring is not found, it returns string::npos.

Let’s look at a basic program that uses string::find to check the position of a substring:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string mainStr = "Hello, this is CodeLessons!";
  size_t pos = mainStr.find("CodeLessons");

  if(pos != string::npos) {
      cout << "Found 'CodeLessons' at position: " << pos << endl;
  } else {
      cout << "Couldn't find 'CodeLessons'." << endl;
  }

  return 0;
}

When you run the above code, you’ll get:

Found 'CodeLessons' at position: 15

Behind the Scenes of string::find

It might seem complicated at first, but string::find operates on a pretty straightforward principle. It scans the main string and looks for the first character of the substring. Once found, it checks if the following characters match the substring. If all characters match, it returns the position. If not, it continues the search.

However, what if the substring exists multiple times in the main string? string::find will only give you the position of the first occurrence. If you need to find all occurrences, you would need to run string::find in a loop, updating the pos parameter each time.

Crafting a Simple String Search Function

For fun and to understand the underlying concept, let’s build a basic version of the string::find function. We’ll name our function simpleFind.

#include <iostream>
#include <string>
using namespace std;

size_t simpleFind(const string& mainStr, const string& subStr) {
    for(size_t i = 0; i <= mainStr.length() - subStr.length(); i++) {
        size_t j;
        for(j = 0; j < subStr.length(); j++) {
            if(mainStr[i + j] != subStr[j]) {
                break;
            }
        }
        if(j == subStr.length()) {
            return i;
        }
    }
    return string::npos;
}

int main() {
    string text = "Welcome to CodeLessons's tutorial!";
    size_t found = simpleFind(text, "tutorial");

    if(found != string::npos) {
        cout << "Found 'tutorial' at position: " << found << endl;
    } else {
        cout << "Couldn't find 'tutorial'." << endl;
    }

    return 0;
}

Running the program should produce:

Found 'tutorial' at position: 25

Our simpleFind function works, but keep in mind it’s a basic version. The built-in string::find function is optimized for performance and handles edge cases better.

Wrapping Up

string::find is an indispensable tool for working with strings in C++. It provides a simple, efficient way to search for substrings. Understanding how it works, and even how to replicate its basic functionality, is essential for anyone working with text data in C++. Whether you’re building a search engine or just doing some simple string manipulations, string::find is your trusty companion.

Exercises

  1. Basic Usage of string::find:
    Write a C++ program that prompts the user to enter a main string and a substring. Use the string::find method to search for the substring within the main string and display the position of the substring if found. If the substring is not found, output an appropriate message.

  2. Finding All Occurrences of a Substring:
    Building upon the first program, modify it to display the positions of all occurrences of the substring within the main string. You will need to use a loop and the pos parameter of the string::find method. Display each position on a new line.

  3. Comparing string::find and simpleFind Functions:
    Using the provided simpleFind function in the article, write a program that compares the results of the built-in string::find and the custom simpleFind function. The program should:

    • Prompt the user for a main string and a substring.
    • Use both methods to search for the substring.
    • Display the positions returned by each method.
    • If the results are the same, display “Both methods returned the same result.”, otherwise display “The methods returned different results.”

Discussion

© 2023, codelessons.dev