2017-10-19 7 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::atstd::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` 

私はそこに残しています1つの落とし穴があります:行の最後に、最終的なスペースへの対処が。

関連する問題