OneBite.Dev - Coding blog in a bite size

Search For A Character In A String In C++

Code snippet for how to Search For A Character In A String In C++ with sample and detail explanation

In the vast ocean of programming, where manipulation and extraction of information can often be a task, the ability to search for a character in a string in C++ plays a significant role. This article will guide you on how to execute such a function in simple and easy-to-follow steps.

Code snippet for Search For A Character In A String In C++

Here’s a simple C++ code snippet to search for a character in a string:

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

int main(){
    string str = "Hello, World!";
    char search_char = 'o';
    size_t found = str.find(search_char);

    if (found != string::npos)
        cout << "Character " << search_char <<" is found at: "<< found << endl;
    else
        cout << "Character " << search_char <<" not found." << endl;

    return 0;
}

Code Explanation for Search For A Character In A String In C++

The program starts with including the necessary header files. #include<iostream> and #include<string> are used to include in our program the standard C++ libraries for I/O streams and string functions respectively.

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

Then we have the main function where the string is defined and the character to search within the string is also defined.

    string str = "Hello, World!";
    char search_char = 'o';

Here, the string “Hello, World!” is our targeted string and the character ‘o’ is the character we are looking for.

The str.find(search_char) function is used to find our desired character in the string. It returns the position of first occurrence of the required character.

    size_t found = str.find(search_char);

This function returns std::string::npos if the character is not found, otherwise it returns the position of the occurrence. We check for this in an if-else statement.

    if (found != string::npos)
        cout << "Character " << search_char <<" is found at: "<< found << endl;
    else
        cout << "Character " << search_char <<" not found." << endl;

If the character is found, the position of the character is displayed. If not found, an appropriate message is also displayed accordingly.

Hence, this is how you search for a character in a string in C++. Remember, practice is key. Keep coding and exploring!

c-plus-plus