如何在C++中的空格处换行

How do you wrap text at a space in C++

本文关键字:空格 换行 C++      更新时间:2023-10-16

我正在尝试制作一个文本包装函数,该函数将在包装之前接收一个字符串和要计数的字符数量。如果可能的话,我想通过寻找以前的空间并在那里包装来避免任何单词被切断。

#include <iostream>
#include <cstddef>
#include <string>
using namespace std;
string textWrap(string str, int chars) {
string end = "n";
int charTotal = str.length();
while (charTotal>0) {
    if (str.at(chars) == ' ') {
        str.replace(chars, 1, end);
    }
    else {
        str.replace(str.rfind(' ',chars), 1, end);
    }
    charTotal -= chars; 
}
return str;
}
int main()
{
    //function call
    cout << textWrap("I want to wrap this text after about 15 characters please.", 15);
    return 0;
}

将 std::string::at 与 std::string::rfind 结合使用。替换location 个字符右侧的空格字符的部分代码是:

std::string textWrap(std::string str, int location) {
    // your other code
    int n = str.rfind(' ', location);
    if (n != std::string::npos) {
        str.at(n) = 'n';
    }
    // your other code
    return str;
}
int main() {
    std::cout << textWrap("I want to wrap this text after about 15 characters please.", 15);
}

输出为:

我要包装
请在此文本后大约 15 个字符。

对字符串的其余部分重复此操作。

有一种比自己搜索空间更简单的方法:

Put the line into a `istringstream`. 
Make an empty `ostringstream`. 
Set the current line length to zero.
While you can read a word from the `istringstream` with `>>`
    If placing the word in the `ostringstream` will overflow the line (current line 
    length + word.size() > max length)
        Add an end of line `'n'` to the `ostringstream`.
        set the current line length to zero.
    Add the word and a space to the `ostringstream`.
    increase the current line length by the size of the word.
return the string constructed by the `ostringstream`

我在那里留下了一个陷阱:处理行尾的最后一个空格。