This post will discuss how to find the index of a character in a string in C++.

1. Using string::find

The string::find member function returns the index of the first occurrence of the specified character in a string, or string::npos if the character is not found. The following example shows invocation of this function:

Download  Run Code

Output:

Character found at index 1

 
Here’s an equivalent version using the std::find standard algorithm, which accepts a range to search for the specified element and returns an iterator to the first element in it.

Download  Run Code

Output:

Character found at index 1

2. Using std::string_view

C++17 allows forming a string view of a character literal using std::literals::string_view_literals::operator""sv, declared in the header <string_view>. After getting the string view, we can use the find() function to get the position of the first character of the given character sequence, or std::string::npos if it is not found. For example,

Download Code

Output:

Character found at index 1

That’s all about finding the index of a character in a string in C++.