一、题目:
二、读题:
对于前后两句中,如果都压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;
}