【问题标题】:how to split a string into lines, without breaking the words?如何在不破坏单词的情况下将字符串拆分为行?
【发布时间】: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>?。然后你可能想搜索关于自动换行的算法。
  • 您如何决定将Iam 放在一起?
  • @Code-Apprentice "希望将字符串拆分为 5 个字符长"
  • akid,如果你的一个词超过 5 个字符,你会怎么做?例如。 “问题”。这是一个您似乎没有考虑过的重要问题,并且对您的解决方案有一些影响。除此之外,您需要寻找一种如您所描述的那样将您的处理分成多个阶段的方法。理想的解决方案是读取输入,直到您对当前输出行所需的一切感到满意为止。让它工作的技巧需要NOT逐个字符地构建输出字符串,而是跟踪位置,然后根据你跟踪的内容复制子字符串。

标签: c++ string c++11


【解决方案1】:

我不确定我是否理解您的“

#include <iostream>
#include <vector>

void main()
{
    std::string szSentence = "I am going to CUET";
    std::vector<std::string> vWords;

    while(szSentence.length() > 0)
    {
        if (szSentence.substr(0, szSentence.find(" ")).length() >= 5)
            vWords.push_back(szSentence.substr(0, szSentence.find(" ")));

        if (szSentence.find(" ") != std::string::npos)
            szSentence = szSentence.substr(szSentence.find(" ")+1);
        else
            szSentence = "";
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2011-08-27
    • 1970-01-01
    • 2021-01-05
    • 2011-10-05
    • 2019-10-04
    • 1970-01-01
    相关资源
    最近更新 更多