gpt4 book ai didi

c++ - wordwap 函数修复以保留单词之间的空格

转载 作者:行者123 更新时间:2023-11-28 07:49:06 25 4
gpt4 key购买 nike

前段时间我在寻找一个片段来为一定大小的行长度做自动换行而不打断单词。它工作得很好,但现在当我开始在编辑控件中使用它时,我注意到它会占用中间的多个空白符号。如果 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

最佳答案

我不是一次读取一个单词,然后添加单词直到超过所需的行长度,而是从您要换行的位置开始,然后向后工作直到找到空白字符,然后将整个 block 添加到输出中。

#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;

关于c++ - wordwap 函数修复以保留单词之间的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14222870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com