2016-07-03 4 views
1

N.B:problem I had a few years agoに直接接続していますが、最初に問題を解決したいのですが、これは質問の一部ではなかったので、私の以前の質問と重複しないようにしてください。文字列のセンタリング機能で特定の文字列を無視するにはどうすればよいですか?

std::string center(std::string input, int width = 113) { 
    return std::string((width - input.length())/2, ' ') + input; 
} 

ゲームサーバの変更を作成するために、私はゲームのSDKを使用しています、このゲーム:

は、私は(113文字)与えられた幅に応じて指定した文字列を中央string centring functionを持っていますSDKは、ゲームのコマンドコンソールのカラー文字列をサポートしています。ドル記号と0〜9の数字(つまり、$1)を使用して表示され、コンソール自体には表示されません。

上記の文字列のセンタリング関数は、これらのマーカーを合計文字列の一部として扱うので、実際に文字列が中央にくるように、これらのマーカーが幅を占める合計文字数を追加します。私は、機能を変更しようとしている

std::string centre(std::string input, int width = 113) { 
    std::ostringstream pStream; 
    for(std::string::size_type i = 0; i < input.size(); ++i) { 
     if (i+1 > input.length()) break; 
     pStream << input[i] << input[i+1]; 
     CryLogAlways(pStream.str().c_str()); 
     if (pStream.str() == "$1" || pStream.str() == "$2" || pStream.str() == "$3" || pStream.str() == "$4" || pStream.str() == "$5" || pStream.str() == "$6" || pStream.str() == "$7" || pStream.str() == "$8" || pStream.str() == "$9" || pStream.str() == "$0") 
      width = width+2; 
     pStream.clear(); 
    } 
    return std::string((width - input.length())/2, ' ') + input; 
} 

上記の機能の目的は、文字列を反復処理現在の文字とostringstreamの隣を追加し、ostringstreamを評価することです。私が望んでいたよう

これは正確にしませんでした。

<16:58:57> 8I 
<16:58:57> 8IIn 
<16:58:57> 8IInnc 
<16:58:57> 8IInncco 
<16:58:57> 8IInnccoom 
<16:58:57> 8IInnccoommi 
<16:58:57> 8IInnccoommiin 
<16:58:57> 8IInnccoommiinng 
<16:58:57> 8IInnccoommiinngg 
<16:58:57> 8IInnccoommiinngg C 
<16:58:57> 8IInnccoommiinngg CCo 
<16:58:57> 8IInnccoommiinngg CCoon 
<16:58:57> 8IInnccoommiinngg CCoonnn 
<16:58:57> 8IInnccoommiinngg CCoonnnne 

(サーバログから抜粋)

をここに問題の簡単な要約です:

enter image description here

私は反復がどのように機能するのか分からないかもしれないと思う。何が欠けているのですか?この機能を私が望むように機能させるにはどうしたらいいですか?

+0

私はあなたが一度に2つを反復することができないとして、あなたが他のすべての文字列を表示することができると思います。 –

答えて

1

あなたが実際にやろうとしているのは、Nが10進数の場合、文字列の$Nというインスタンスを数えることです。これを行うには、std::string::findを使用して文字列内の$を探し、次の文字が数字かどうかを確認します。

std::string::size_type pos = 0; 
while ((pos = input.find('$', pos)) != std::string::npos) { 
    if (pos + 1 == input.size()) { 
     break; // The last character of the string is a '$' 
    } 
    if (std::isdigit(input[pos + 1])) { 
     width += 2; 
    } 
    ++pos; // Start next search from the next char 
} 

std::isdigitを利用するためには、最初に行う必要があります。

#include <cctype> 
関連する問題