敲笨钟ptaC++

简介: 敲笨钟ptaC++

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;
  }
}

就是还有两个用例通不过,希望有大佬可以指出

相关文章
|
1月前
|
C++
【PTA】L1-016 验证身份(C++)
【PTA】L1-016 验证身份(C++)
53 0
【PTA】L1-016 验证身份(C++)
|
21天前
|
存储 C++
【PTA】L1-039 古风排版(C++)
【PTA】L1-039 古风排版(C++)
10 1
|
1月前
|
Java C++
部落(pta)(并查集) Java以及C++
部落(pta)(并查集) Java以及C++
23 2
|
21天前
|
存储 人工智能 C++
【PTA】L1-064 估值一亿的AI核心代码(详C++)
【PTA】L1-064 估值一亿的AI核心代码(详C++)
15 1
|
21天前
|
存储 C++ 索引
【PTA】L1-059 敲笨钟(C++)
【PTA】L1-059 敲笨钟(C++)
11 1
|
21天前
|
存储 人工智能 C++
【PTA】L1-093 猜帽子游戏(C++)
【PTA】L1-093 猜帽子游戏(C++)
18 1
|
21天前
|
C++
【PTA】L1-046 整除光棍(C++)
【PTA】L1-046 整除光棍(C++)
11 1
|
21天前
|
存储 C++
【PTA】L1-043 阅览室(C++)
【PTA】L1-043 阅览室(C++)
13 1
|
21天前
|
存储 C++
【PTA】​L1-034 点赞(C++)
【PTA】​L1-034 点赞(C++)
9 0
|
1月前
|
前端开发 JavaScript 测试技术
【PTA】L1-32 Left-pad (C++)
【PTA】L1-32 Left-pad (C++)
24 0
【PTA】L1-32 Left-pad (C++)