修复/改进换行功能
Fix/Improve 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.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
*/
相关文章:
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 在 Stream C++ 文本之前有一个额外的换行符
- 流:CSV 文件中的换行符
- 将缓冲区复制到剪贴板 [换行错误]
- 如何在三元条件运算符中添加换行符和连接? :在 C++ 中
- Clang-格式:在多行语句之后的换行符上打开大括号
- 如何正确转发/换行static_cast?
- 在输出流中插入换行符
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- QProcess::readAllStandardOutput() 和换行符
- 如果有换行符,clang 格式不会附加大括号
- 创建一个简单的前向迭代器,该迭代器在循环缓冲区的"end"处自动换行
- C++在标点符号后将字符串换行
- 提取后返回换行符的C++istream.get()
- 如何在出现换行符之前将多个整数作为输入?
- 正则表达式 获取两个换行符之间的文本
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 修复/改进换行功能