[GESP202609 三级]分割字符串
2026-09-18 22:01:46
发布于:湖北
10阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int main() {
string a;
getline(cin, a);
// 先检查是否能做第一次分割(是否存在至少1个空格)
bool splittable = (a.find(' ') != string::npos);
// 若连一个空格都没有,无法分割,直接输出本身
if (!splittable) {
cout << a << "\n";
return 0;
}
int need = 1; // 当前需要的连续空格数
int cnt = 0; // 当前连续空格累计
for (int i = 0; i < a.length(); i++) {
if (a[i] == ' ') {
cnt++;
if (cnt == need) { // 达到分割所需连续空格数 → 换行截止
cout << '\n';
cnt = 0;
need++;
}
// 未达到 need 时:先不输出,等后续决定
}
else {
// 处理之前累计但未组成分割的空格:原样输出
if (cnt > 0) {
for (int j = 0; j < cnt; j++) cout << ' ';
cnt = 0;
}
cout << a[i]; // 输出非空格字符
}
}
// 末尾如果有残留空格(题目已保证不以空格结尾,所以一般没有)
if (cnt > 0) {
for (int j = 0; j < cnt; j++) cout << ' ';
}
cout << '\n';
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
getline(cin, s);
int need = 1; // 当前需要连续的空格数
vector<string> res; // 存储每段结果
while(true){
// 找连续 need 个空格的位置
int pos = -1;
for(int i=0; i+need-1 < s.length(); i++){
bool ok = true;
for(int j=0; j<need; j++){
if(s[i+j]!=' ') { ok=false; break; }
}
if(ok){ pos = i; break; }
}
if(pos == -1) break; // 无法再分割
string left = s.substr(0, pos);
string right = s.substr(pos+need);
res.push_back(left);
s = right;
need++;
}
// 输出所有 left 及最后一次 right
for(int i=0; i<res.size(); i++) cout << res[i] << "\n";
cout << s << "\n";
return 0;
}
这里空空如也




有帮助,赞一个