如何用C ++

时间:2017-10-19 17:42:21

标签: c++ string textwrapping

我正在尝试创建一个文本换行函数,它将在换行前接收一个字符串和一定数量的字符。如果可能的话,我想通过寻找之前的空间并将其包裹起来来保持切断任何一个词。

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

2 个答案:

答案 0 :(得分:2)

std::string::atstd::string::rfind结合使用。替换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); } th 字符右侧空格字符的部分代码是:

hasil = (TextView) findViewById(R.id.HASIL_ID);

输出结果为:

  

我想包裹   请大约15个字后的这个文字。

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

答案 1 :(得分:2)

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

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`

有一个我要离开的地方:处理行尾的最后一个空格。