wordwap函数修复以保留单词之间的空白

时间:2013-01-08 19:47:34

标签: c++ word-wrap istringstream

前段时间我正在寻找一个片段来为一定长度的行长做一个自动换行而不会破坏这些单词。它工作得很公平,但是现在当我开始在编辑控件中使用它时,我注意到它在中间吃掉了多个空白符号。如果wstringstream不适合任务,我正在考虑如何解决它或完全摆脱它。也许那里有人有类似的功能?

void WordWrap2(const std::wstring& inputString, std::vector<std::wstring>& outputString, unsigned int lineLength)
{
   std::wstringstream  iss(inputString);
   std::wstring line;
   std::wstring word;

   while(iss >> word)
   { 
      if (line.length() + word.length() > lineLength)
      {
         outputString.push_back(line+_T("\r"));
         line.clear();
      }
      if( !word.empty() ) {
      if( line.empty() ) line += word; else line += +L" " + word;
      }

   }

   if (!line.empty())
   { 
      outputString.push_back(line+_T("\r"));
   }
}

换行符分隔符号应保持为\r

2 个答案:

答案 0 :(得分:1)

不是一次读一个单词,而是在你超过所需的行长度之前添加单词,我会从你想要换行的点开始,然后向后工作直到你找到一个空白字符,然后将整个块添加到输出中。

#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>

void WordWrap2(const std::wstring& inputString, 
               std::vector<std::wstring>& outputString, 
               unsigned int lineLength) {
    size_t last_pos = 0;
    size_t pos;

    for (pos=lineLength; pos < inputString.length(); pos += lineLength) {

        while (pos > last_pos && !isspace((unsigned char)inputString[pos]))
            --pos;

        outputString.push_back(inputString.substr(last_pos, pos-last_pos));
        last_pos = pos;
        while (isspace((unsigned char)inputString[last_pos]))
            ++last_pos;
    }
    outputString.push_back(inputString.substr(last_pos));
}

就目前而言,如果它遇到的单个字长于你指定的行长,则会失败(在这种情况下,它可能应该只是在单词的中间断开,但它目前没有。)

我还写过它以跳过字段之间的空格,当它们在换行符时发生。如果你真的不想那样,那就消除:

        while (isspace((unsigned char)inputString[last_pos]))
            ++last_pos;

答案 1 :(得分:0)

如果您不想丢失空格字符,则需要在执行任何读取之前添加以下行:

iss >> std::noskipws;

然后使用带有字符串作为第二个参数的>>将无法正常工作w.r.t.空格。

你不得不求助于阅读字符,并自己管理它们。

相关问题