L1-059 敲笨钟

一、题目:

二、读题:

对于前后两句中,如果都压ong音,就把最后三个字符串替换成“qiao ben zhong”。

三、思路:

find ',' 和 ‘.’

        auto found1 = words.find(',');
        string a = words.substr(found1 - 3, 3); //通过找逗号
        string b = words.substr(words.size() - 4, 3); //通过找句号:字符串大小-1 表示最后一个字符

 进行if判断 : if (a == "ong" && b == "ong")

替换:通过反向迭代器找到倒数第三个空格,使用respace函数替换。

但是要注意,由图可知,respace不支持反向迭代器参数,我们需要先把他转成正向迭代器。

 反向迭代器转成正向迭代器,需要用到base函数

在C++中,base()成员函数是std::reverse_iterator类的一个成员函数,它的作用是将一个反向迭代器转换为其对应位置的正向迭代器。这种转换在处理反向迭代器时非常有用,因为许多标准库函数和容器成员函数只接受正向迭代器作为参数。 

string::iterator it = rit.base();

 respace 可以传入迭代器区间,半闭半开。字符串长度可以不一样长!

四、源码:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    int n;
    cin >> n;
    getchar();
   while (n--)
    {
        string words;
        getline(cin, words);
        auto found1 = words.find(',');
        string a = words.substr(found1 - 3, 3);
        string b = words.substr(words.size() - 4, 3);
        //cout << a << " " << b << endl;
        if (a == "ong" && b == "ong")
        {
            string::reverse_iterator rit = words.rbegin();
            int count = 0;
            while (rit != words.rend())
            {
                if (*rit == ' ') count++;
                if (count == 3)
                {
                    //cout << *rit << " " << *(words.end()-1);
                    string::iterator it = rit.base();  //base作用是把反向迭代器变成正向
                    words.replace(it, words.end(), "qiao ben zhong."); //replace中,不能用反向迭代器的参数
                    cout << words << endl;
                    break;
                }
                ++rit;
            }
        }
        else {
            cout << "Skipped" << endl;
        }

    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值