#include <iostream>
#include <sstream>
#include <string>
#include <vector>
/*
wrap_text()
-----------
Wraps a given string into lines of maximum width `w`.
Approach:
- Use std::istringstream to extract words efficiently.
- Build lines by appending words until adding another would exceed width.
- Push completed lines into a vector.
- Join lines with newline characters.
This avoids manual character-by-character scanning and uses
standard library tools for clarity and performance.
*/
std::string wrap_text(const std::string& text, std::size_t w) {
std::istringstream iss(text); // Stream for reading words
std::string word;
std::string line;
std::vector<std::string> lines;
while (iss >> word) {
// If the current line is empty, start it with the word
if (line.empty()) {
line = word;
}
// Otherwise check if adding the next word exceeds width
else if (line.size() + 1 + word.size() <= w) {
line += " " + word;
}
// If it exceeds width, push the current line and start a new one
else {
lines.push_back(line);
line = word;
}
}
// Push the last line if not empty
if (!line.empty()) {
lines.push_back(line);
}
// Join lines into a single string separated by '\n'
std::string result;
for (std::size_t i = 0; i < lines.size(); ++i) {
result += lines[i];
if (i + 1 < lines.size()) {
result += "\n";
}
}
return result;
}
int main() {
std::string sample =
"C++ provides powerful standard library tools for handling strings. "
"This program demonstrates how to wrap text cleanly and efficiently.";
std::string wrapped = wrap_text(sample, 35);
std::cout << wrapped << "\n";
}
/*
run:
C++ provides powerful standard
library tools for handling strings.
This program demonstrates how to
wrap text cleanly and efficiently.
*/