开发者

Fix/Improve Word Wrap Function

I have a simple word wrap function that takes a long string as an input and then breaks that string into smaller strings and adds them to an array to be outputted later. Right now the last word or two isn't outputting. That's the main problem. However, I would also like to improve the function. I know it's kind of messy. I was wondering if there are any better ways of solving this problem. I think the array is unnecessary but I don't know how else to do it. After the array is filled with all the smaller strings, I just output them to a text file. Any suggestions would be greatly appreciated.

Here's the Word Wrap function:

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.le开发者_StackOverflow社区ngth() + outWord.length() > max)
            {
                formatedAr[word] = outLine;
                word++;
                outLine.clear();
            }
            outLine += outWord + " ";
            outWord.clear();
        }
    }
    formatedAr[word] = outLine;
}

And this is where I call the function and output the array:

WordWrap(dvdPtr -> synopsis, formatedAr, SIZE);

index = 0;

while(index < SIZE && formatedAr[index] != "")
{
    outFile << formatedAr[index] << endl;
    index++;
}


Here is an example code.

#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
*/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜