【问题标题】:Fix/Improve Word Wrap Function修复/改进自动换行功能
【发布时间】:2011-04-28 07:32:43
【问题描述】:

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

这里是自动换行功能:

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++;
}

【问题讨论】:

  • 你试过调试你的程序吗?你学到了什么?
  • 您可以使用 std::vector 代替固定大小的数组 formatedAr。您还可以使用 strtok(参见 msdn.microsoft.com/en-us/library/2c8d19sb.aspx)来标记您的输入文本。

标签: c++ function word-wrap


【解决方案1】:

这是一个示例代码。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多