修复/改进换行功能

Fix/Improve Word Wrap Function

本文关键字:换行 功能 修复      更新时间:2023-10-16

我有一个简单的换行函数,它接受一个长字符串作为输入,然后将该字符串分解成更小的字符串,并将它们添加到稍后输出的数组中。现在,最后一两个单词没有输出。这是主要问题。但是,我也想改进这个功能。我知道这有点乱。我想知道是否有更好的方法来解决这个问题。我认为数组是不必要的,但我不知道怎么做。在用所有较小的字符串填充数组之后,我将它们输出到一个文本文件。如有任何建议,不胜感激。

换行函数:

void WordWrap(string inputString, string formatedAr[], const int SIZE)
{
    unsigned int index;
    unsigned int word;
    unsigned int max = 65;
    string outWord;
    string outLine;
    outWord = "";
    outLine = "";
    word = 0;
    for(int i = 0; i < SIZE; i++)
    {
        formatedAr[i] = "";
    }
    for(index = 0; index <= inputString.length(); index++)
    {
        if(inputString[index] != ' ')
        {
            outWord += inputString[index];
        }
        else
        {
            if(outLine.length() + outWord.length() > max)
            {
                formatedAr[word] = outLine;
                word++;
                outLine.clear();
            }
            outLine += outWord + " ";
            outWord.clear();
        }
    }
    formatedAr[word] = outLine;
}

这就是我调用函数并输出数组的地方:

WordWrap(dvdPtr -> synopsis, formatedAr, SIZE);
index = 0;
while(index < SIZE && formatedAr[index] != "")
{
    outFile << formatedAr[index] << endl;
    index++;
}

下面是一个示例代码。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
void WordWrap(const string& inputString, vector<string>& outputString, unsigned int lineLength)
{
   istringstream iss(inputString);
   string line;
   do
   {
      string word;
      iss >> word;
      if (line.length() + word.length() > lineLength)
      {
         outputString.push_back(line);
         line.clear();
      }
      line += word + " ";
   }while (iss);
   if (!line.empty())
   {
      outputString.push_back(line);
   }
}
/*
A simple test:
Input string: "aaa bbb ccccccc dddd d111111111111111 33333 4444444444 222222222  ajdkjklad 341343"
Length per line: 20
Output lines of strings:
Line 1: aaa bbb ccccccc dddd
Line 2: d111111111111111
Line 3: 33333 4444444444
Line 4: 222222222  ajdkjklad
*/