2017-03-26 25 views
-1

比方說,我們有我們要分割字符串爲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

+2

首先請閱讀[爲什麼我不應該#include ?](http://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h)。那麼你可能想要搜索關於*自動換行*的算法。 –

+0

你如何決定將'I'和'am'保持在一起? –

+0

@ Code-Apprentice「希望將字符串分成5個字符長」 –

回答

0

我不知道,我明白你的「< = 5長」檢查,但這裏是我的觀點:

#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 = ""; 
    } 
} 
相關問題