Find The Position Of The Last Occurrence Of A Substring In A String In C++
Code snippet for how to Find The Position Of The Last Occurrence Of A Substring In A String In C++ with sample and detail explanation
Finding the position of each character or a particular sequence of characters, also known as a substring, in a string is a common task when handling strings in C++. In this article, we are going to write a simple code that allows developers to find the position of the last occurrence of a substring in a string.
Code snippet: Finding the Last Occurrence of a Substring
Here is the C++ code snippet for finding the last occurrence of a substring in a string.
#include <iostream>
#include <string>
int main() {
std::string str = "Hello world, welcome to the world of C++.";
std::string substring = "world";
size_t pos = str.rfind(substring);
if(pos != std::string::npos) {
std::cout << "Last occurrence is at: " << pos << std::endl;
} else {
std::cout << "Substring not found." << std::endl;
}
return 0;
}
Code Explanation for Finding the Last Occurrence of a Substring
To begin, we include the necessary libraries, iostream for input-output stream and string for string operations.
#include <iostream>
#include <string>
Next, in the main function, we define our sample string str
and the substring
we want to find the last occurrence of.
std::string str = "Hello world, welcome to the world of C++.";
std::string substring = "world";
We then use the rfind()
function provided by the C++ standard string class. This function returns the highest index where the substring is found. If the substring is not found, it returns std::string::npos
.
size_t pos = str.rfind(substring);
Finally, we check whether a position has been found. If pos
is not equal to std::string::npos
, this means a match for the substring was found, so we print out the position. Otherwise, we inform the user that the substring was not found.
if(pos != std::string::npos) {
std::cout << "Last occurrence is at: " << pos << std::endl;
} else {
std::cout << "Substring not found." << std::endl;
}
By running the program with different strings and substrings, you can clearly understand how it works. We can adjust the code depending on the specific requirements of your tasks.