【问题标题】:Truncate string c++ to length without cutting word将字符串 c++ 截断为长度而不剪切单词
【发布时间】:2016-02-21 20:04:02
【问题描述】:

我输入了一个 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个会怎样?
  • “但我不确定这是解决问题的最佳方法” 您的代码根本没有解决问题
  • -if(index==0) 的目的是 64 个连续的非空格字符 - 我忘了声明 index 是一个 int - πάντα ῥεῖ 你能解释一下我的错误吗?
  • 您不需要S.at(index),因为您已明确检查index 是否在界限内。只需使用S[index]

标签: c++ string split word


【解决方案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);

这个版本不擅长空格字符;您可能应该在推回时将它们移除。但这是另一回事。

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

【讨论】:

  • 有一种情况是无限循环,我们可以在 pos=0 处留空间(截断后特殊),它认为更好的解决方案是在 pos+1 处截断
【解决方案2】:

这是我的尝试:

必须捕获空字符串或单个单词>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;

 }

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

【讨论】:

  • 谢谢您的回答;但是如果第一个词长于 64 它将被推入向量 no?
猜你喜欢
  • 1970-01-01
  • 2011-10-02
  • 1970-01-01
  • 2019-07-30
  • 2019-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多