The C++ find_last_of() member function program example part II
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Searches through a string for the last character that matches any element of a specified string using find_last_of() in C++ programming part II
To show: How to search through a string for the last character that matches any element of a specified string using he find_last_of() in C++ programming part II
// the C++ find_last_of() example part II
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
// searching a string for a substring as specified by a C-string
string str3("Testing 1234 Testing 1234");
cout<<"str3 string is: "<<str3<<endl;
basic_string <char>::size_type index5;
static const basic_string <char>::size_type npos = -1;
const char *cstr2 ="s1";
index5 = str3.find_last_of(cstr2, 20, 20);
cout<<"Operation: str3.find_last_of(cstr2, 20, 20)"<<endl;
if(index5 != npos)
cout<<"The index of the last occurrence of an "
<<"element of 's1' in str3 before the 20th "
<<"position is: "<<unsigned int(index5)<<endl;
else
cout<<"Elements of the substring 's1' were not\n"
<<"found in str3 before the 20th position."<<endl;
cout<<endl;
// searching a string for a substring as specified by a string
string str4("Testing 1234 Testing 1234");
cout<<"str4 string is: "<<str4<<endl;
basic_string <char>::size_type index6, index7;
string str5("416");
index6 = str4.find_last_of(str5, 25);
cout<<"Operation: str4.find_last_of(str5, 25)"<<endl;
if(index6 != npos)
cout<<"The index of the last occurrence of an "
<<"element of '416' in str4 before the 25th "
<<"position is: "<<unsigned int(index6)<<endl;
else
cout<<"Elements of the substring '416' were not\n"
<<"found in str4 after the 0th position"<<endl;
string str6("1g");
index7 = str4.find_last_of(str6);
cout<<"\nOperation: str4.find_last_of(str6)"<<endl;
if(index7 != npos)
cout<<"The index of the last occurrence of an "
<<"element of '1g' in str4 before the 0th "
<<"position is: "<<unsigned int(index7)<<endl;
else
cout<<"Elements of the substring '1g' were not\n"
<<"found in str4 after the 0th position"<< endl;
return 0;
}
Output example:
str3 string is: Testing 1234 Testing 1234
Operation: str3.find_last_of(cstr2, 20, 20)
The index of the last occurrence of an element of 's1' in str3 before the 20th position is: 20
str4 string is: Testing 1234 Testing 1234
Operation: str4.find_last_of(str5, 25)
The index of the last occurrence of an element of '416' in str4 before the 25th position is: 24
Operation: str4.find_last_of(str6)
The index of the last occurrence of an element of '1g' in str4 before the 0th position is: 21
Press any key to continue . . .