【发布时间】:2017-03-26 09:35:05
【问题描述】:
假设我们有一个字符串,我们希望将字符串拆分为 5 个字符长而不拆分单个单词:
I am going to CUET
现在,如果我们可以通过以下方式拆分它:
I am
going
to
CUET
我为此编写了一个代码。首先,我将字符串分解为单词并将它们保存到向量中,然后取出每个单词并检查它是否小于 5。如果没有,那么我将字符串添加到 ans 向量中。 这是我的代码:
#include<bits/stdc++.h>
using namespace std;
vector<string>split(string txt)
{
vector<string>result;
string s="";
for(int i=0; i<=txt.size();i++)
{
if( i<txt.size() and txt[i]!=' ')
s+=txt[i];
else
{
result.push_back(s);
s="";
}
}
return result;
}
int main()
{
string str="I am going to CUET";
int len=5;
vector<string>result=split(str);
vector<string>ans;
int i=0;
string s="";
while(i<result.size())
{
if(i<result.size() and s.size()+result[i].size()<=len)
{
if(s=="") s+=result[i];
else s+=" ",s+=result[i];
i++;
}
else
{
ans.push_back(s);
s="";
}
}
if(s!="") ans.push_back(s);
for(int i=0; i<ans.size();i++) cout<<ans[i]<<endl;
}
有没有比我更好的解决方案,或者有更好的解决方案而不先打破这个词?
编辑:这是我的解决方案,没有先破坏这个词:http://ideone.com/IusYhE
【问题讨论】:
-
首先请阅读Why should I not #include <bits/stdc++.h>?。然后你可能想搜索关于自动换行的算法。
-
您如何决定将
I和am放在一起? -
@Code-Apprentice "希望将字符串拆分为 5 个字符长"
-
akid,如果你的一个词超过 5 个字符,你会怎么做?例如。 “问题”。这是一个您似乎没有考虑过的重要问题,并且对您的解决方案有一些影响。除此之外,您需要寻找一种不如您所描述的那样将您的处理分成多个阶段的方法。理想的解决方案是读取输入,直到您对当前输出行所需的一切感到满意为止。让它工作的技巧需要NOT逐个字符地构建输出字符串,而是跟踪位置,然后根据你跟踪的内容复制子字符串。