#include <iostream>
#include <string>
using namespace std;
void test_getline(void)
{
string s1;
cout << "Enter a sentence (use <space> as the delimiter): "<<endl;
getline(cin,s1, ' ');
cout << "You entered: " << s1 << endl;
cout << "Enter a sentence (use <Enter> as the delimiter): "<<endl;
getline(cin,s1, '\n');
cout << "You entered: " << s1 << endl;;
}
/***************
运行结果:
Enter a sentence (use <space> as the delimiter):
think out of the box
You entered: think
Enter a sentence (use <Enter> as the delimiter):
You entered: out of the box
****************/
void test_find_first_of(void)
{
string str ("Replace the vowels in this sentence by asterisks.");
size_t found;
found=str.find_first_of("aeiou");
while (found!=string::npos)
{
str[found]='*';
found=str.find_first_of("aeiou",found+1);
}
cout << str << endl;
}
/***************
运行结果:
R*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.
****************/
void test_find_first_not_of(void)
{
string str("look for non-alphabetic characters...");
size_t found;
found=str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
if (found!=string::npos)
{
cout << "First non-alphabetic character is " << str[found];
cout << " at position " << int(found) << endl;
}
}
/***************
运行结果:
First non-alphabetic character is - at position 12
****************/
int main (int argc, char** argv)
{
test_getline();
cout<<endl<<"******************************************"<<endl;
test_find_first_of();
cout<<endl<<"******************************************"<<endl;
test_find_first_not_of();
cout<<endl<<"******************************************"<<endl;
const string delims(" \t,.;");
string line;
cout<<"\nplease input a sentence :\n";
// for every line read successfully
while (getline(cin,line))
{
cout<<"\nafter reverse:\n";
string::size_type begIdx, endIdx;
// search beginning of the first word
begIdx = line.find_first_not_of(delims);
// while beginning of a word found
while (begIdx != string::npos)
{
// search end of the actual word
endIdx = line.find_first_of (delims, begIdx);
if (endIdx == st