C++ 标准模板库学习之 string 类 详解 (一) 将一个句子中每个单词的单词字母顺序翻转 关于npos find_first_not_of find_first_of getline

先看例子程序:

#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
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值