Find index of a character in string in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <string> int main() { std::string s = "C++20"; char c = '+'; int index = s.find(c); if (index != std::string::npos) { std::cout << "Character found at index " << index << std::endl; } else { std::cout << "Character not found" << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string s = "C++20"; char c = '+'; auto it = std::find(s.begin(), s.end(), '+'); if (it != s.end()) { int index = std::distance(s.begin(), it); std::cout << "Character found at index " << index << std::endl; } else { std::cout << "Character not found" << std::endl; } return 0; } |
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,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string_view> using namespace std::string_view_literals; int main() { size_t index = "C++20"sv.find('+'); if (index != std::string::npos) { std::cout << "Character found at index " << index << std::endl; } else { std::cout << "Character not found" << std::endl; } return 0; } |
Output:
Character found at index 1
That’s all about finding the index of a character in a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)