将字符串 c++ 截断为长度而不切割单词

Truncate string c++ to length without cutting word

我输入了一个 C++ 字符串,如果我的字符串的大小大于 64 个字符,我需要将它切割成更小的字符串(以存储到字符串向量中),但我需要确保不要这样做切一个字;所以我需要在找到空格时拆分;我写了一段代码,但我不确定这是解决问题的最佳方法。 任何帮助将不胜感激;这是我写的代码。

void Truncate_string(string& S; vector<string>& T){
     int index;
     while(S.size()>64 && !S.empty()){
         index=63; // The index where the cut would be made
         while(index>0 && S.at(index)!=' ') --index; 
         if(index==0) index=63; // no space found
         T.push_back(S.substring(0,index));
         S=S.substring(index);
     }
 }

这是我的尝试:

必须捕获边界大小写,例如空字符串或单个单词 >64

void trunc(const std::string& str, std::vector<std::string>& vec)
{
    std::string buf; 
    std::stringstream ss(str); 

    ss >> buf;
    vec.push_back(buf);

    while (ss >> buf)
    {        
        if(vec.back().length() + buf.length() < 64)            
            vec.back() += ' ' + buf;            
        else        
            vec.push_back(buf);

    }
}


 int main()
{
    std::vector<std::string> vec;
    std::string text("AAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAA AAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAA");

     trunc(text, vec);

     for(auto itr : vec)
     {
         std::cout << itr << std::endl;
     }
     return 1;

 }

我确信有更好的迭代器解决方案

对于许多字符串操作问题,答案在标准库中。 std::string 已经有一个成员函数可以做到这一点:

while (S.length() > 64) {
    std::string::size_type pos = S.rfind(' ', 63);
    if (pos == std::string::npos)
        break; // no 64-bit-or-less substring
    else {
        T.push_back(S.substr(0, pos));
        S.erase(0, pos);
    }
}
if (!S.empty())
    T.push_back(S);

这个版本对 space 个字符不智能;您可能应该在回推时移除它们。但那是另一回事。

编辑:这还没有经过仔细审查,因此可能存在差一错误。