#include <string>
#include <iostream>
#include <iomanip>
class StringProcessing
{
public:
StringProcessing() : characterWidth(40),
textToBeFormatted("NULL") {}
inline void initString() {
textToBeFormatted = "text some text some text some text some text some text"
" text some text some text some text some text some text"
" text some text some text some text some text some text"
" text some text some text some text some text some text"
" text some text some text some text some text some text";
}
inline void displayString()
{
const std::string& s = textToBeFormatted;
const int& width = characterWidth;
for (int current = 0; current < s.length();)
{
if (s.length() < width)
{
output(s);
break;
}
if (s.length() - current < width)
{
output(s.substr(current));
break;
}
std::string substr = s.substr(current, width);
current += width;
size_t space = substr.rfind(' ');
if (space != std::string::npos && (substr[width - 1] != ' ' &&
(s.length() > current && s[current] != ' ')))
{
current -= width - space - 1;
substr = substr.substr(0, space + 1);
}
output(substr);
}
}
private:
inline void output(const std::string& s)
{
std::cout << std::setfill(' ') << std::right << std::setw(characterWidth) << s << std::endl;
}
int characterWidth;
std::string textToBeFormatted;
};
int main()
{
StringProcessing sp;
sp.initString();
sp.displayString();
}