2017-10-19 57 views
0

我试图制作一个文本包装函数,它将在包装之前接收一个字符串和一定数量的字符。如果可能的话,我想通过查找以前的空间并包裹在那里来阻止任何词语被切断。如何在C++空间中包装文本

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

你对现有的代码有什么疑问?它不起作用吗?如果是这样,它是如何失败的? – LThode

回答

1

使用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个字符,请。

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

+0

请注意,如果你的单词超过了行长,这将会给出错误的结果;在进行替换之前,你应该检查'std :: string :: npos'和行的开头。 –

1

没有比自己寻找空间更简单的方法:

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` 

有有一个问题我要离开在那里:与上线末端的最终处理的空间。