Find The First Occurrence Of A Character In A String In C++
Code snippet for how to Find The First Occurrence Of A Character In A String In C++ with sample and detail explanation
In C++, there are various methods available to find the first occurrence of a character in a string. In this guide, we will explore how to achieve this using some simple C++ code.
Code snippet to find first occurrence of a character in a string
Here’s a simple C++ code snippet that can help you to find the first occurrence of a character in a string.
#include <iostream>
#include <string>
int main()
{
std::string str = "Example string";
char ch = 'e';
size_t found = str.find(ch);
if (found != std::string::npos)
std::cout << "First occurrence of " << ch << " is found at position: " << found << '\n';
else
std::cout << ch << " is not found in the string.\n";
return 0;
}
Code Explanation to find first occurrence of a character in a string
This code snippet demonstrates a simple C++ program to determine the position of the first occurrence of a specific character in a string.
-
We start by including the necessary libraries:
<iostream>
and<string>
. The<iostream>
library allows us to use std::cout and std::cin, and<string>
enables to us to work with string data type. -
In the
int main()
function, we initialize a stringstr
with the text “Example string” and a characterch
with ‘e’. -
Then, we use the
find()
function from the standard string library. This function returns the position of the first occurrence of the input character in the string. If the character is not found, the function returnsstd::string::npos
. -
The
if
statement checks whether the character was found. Iffound
is not equal tostd::string::npos
, that means the character is present in the string and we print its position. If it matchesstd::string::npos
, that indicates the character was not found in the string, and we print a suitable message. -
Finally,
return 0;
indicates that the program has executed successfully.
This simple yet robust method is an effective way to find the first occurrence of a character in a C++ string.