The C++ char_traits member function, find() to search a string in a forward direction for the first occurrence of a substring that matches a specified sequence of characters program example
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: Using the find() member function to search a string in a forward direction for the first occurrence of a substring that matches a specified sequence of characters
To show: How to search a string in a forward direction for the first occurrence of a substring that matches a specified sequence of characters using find() member function
// the C++ char_traits, find() example
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
const char* result1;
const char* result2;
const char* str = "Testing the char_traits, find()";
cout<<"The string to be searched is:\n"<<str<<endl;
// searching for an 'a' in the first 20 positions of string str
cout<<"\nOperation: find(str, 20, 'a')"<<endl;
result1 = char_traits<char>::find(str, 20, 'a');
cout<<"Searching character \'"<<*result1<<"\'."<<endl;
cout<<"The string beginning with the first occurrence\n"
<<"of the character 'a' is: "<<result1<<endl;
// when no match is found the NULL value is returned
result2 = char_traits<char>::find(str, 20, 'z');
cout<<"\nOperation: find(str, 20, 'z')"<<endl;
if(result2 == NULL)
cout<<"The character 'z' was not found."<<endl;
else
cout<<"The result of the search is: "<<result2<<endl;
return 0;
}
Output example:
The string to be searched is:
Testing the char_traits, find()
Operation: find(str, 20, 'a')
Searching character 'a'.
The string beginning with the first occurrence
of the character 'a' is: ar_traits, find()
Operation: find(str, 20, 'z')
The character 'z' was not found.
Press any key to continue . . .