2017-10-19 3 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::rfind과 조합하여 std::string::at을 사용하십시오. 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` 

내가 거기에 떠날거야 하나 개 잡았다 있습니다 : 라인의 끝 부분에있는 마지막 공간 다루기가.