substr
string a = "123456";
string sub_a = a.substr(0, 2); // "12"string sub_a_ = a.substr(2); // "3456"
- 左闭右开的截取字符串
实现思路
以逗号分割,取出两个字符串。利用substr
判断是否以ong
结尾,然后使用string
流获取每个单词到一个vector
中后改变最后三个索引位置的单词为qiao ben zhong.
#include <iostream>
#include <string>
#include <vector>
#include <sstream>using namespace std;std::string replaceLastThreeWords(std::string input) {string result;// 统计有几个空格int count = 0;for (auto s : input) if (s == ' ') count++;// 计算出开始替换的空格位置int changeLocation = count - 2;count = 0;for (int i = 0; i < input.size(); i++) {if (input[i] == ' ') count++;if (count == changeLocation) {result = input.substr(0, i + 1);result += "qiao ben zhong.";return result;}}return "Skipped";}bool lastWordEndsWithOng(const std::string& str1, const std::string& str2) {if (str1.size() < 3 || str2.size() < 4 || str1.substr(str1.size() - 3) != "ong" || str2.substr(str2.size() - 4) != "ong.")return false;return true;
}int main() {int n;cin >> n;cin.ignore(); // 清除换行符while (n--) {string str;getline(cin, str);// 以逗号为分割size_t slashPos = str.find(',');string str1 = str.substr(0, slashPos);string str2 = str.substr(slashPos + 1);if (!lastWordEndsWithOng(str1, str2)) cout << "Skipped" << endl;else cout << replaceLastThreeWords(str) << endl;}
}
就是还有两个用例通不过,希望有大佬可以指出