How to Search Text in C++


In this article, we show how to search text in C++.

Searching text is something that is very important.

Just think about writing something in a program such as Microsoft Word and then looking for a certain section or word in your text. Being able to use the Search and Find utility is vital, as you probably know.

So C++ has a number of functions to enable this search functionality, so that we can find what we need within text.

So let's now delve into this search functionality in C++.

The most basic function to search text in C++ is the find() function.

The find() function takes in 2 parameters.

The first parameter is the substring that you want to find.

The second parameter is the index number of the character at which to start searching. The second parameter doesn't have to be specified. If you don't specify a second parameter, then by default it will be 0, meaning it will start from the very beginning of the text.

Let's now show how a basic version of this program works.

We will search the string below for the word "water" and see what the program returns.

Let's go over this program now.

So we create a string named string1, and we have our text.

Next what you have to do is create an integer value, which is made in order to hold the value returned by the find() function.

Know that the find() function returns integer values. If the substring isn't at all within the text, it returns -1 as its output. If the substring is found within the text, it returns the integer location of the first character where the substring is found. Remember substrings begin at the integer location of 0 and increment with each character by 1.

So we create the integer variable, value, and it will hold the output of the find() function. This is the standard way of using the find function.

We then output the value of the find() function.

After running this program, we get an output of 12, because the word "water" starts at the index location of 12.

You can also make your program "smarter" by adding in if-else statements to know whether a substring was found.

This is shown in the program below.

So with the find() function, we can see whether a substring exists within a string and can decide where we want to start searching for it in the string.

And this is how to search text in C++.

Related Resources

How to Write Contents to a File in C++

How to Append Contents to a File in C++

HTML Comment Box is loading comments...