1

ブーストを使用せに std::string を作成するための最良の方法と最も簡単な方法を知っています。

たとえば、この文字列を変換する方法

"  a   b          c  d     e '\t' f      '\t'g"

"a b c d e f g"

'\t' が通常の集計であると仮定します。

ありがとう。

4

3 に答える 3

6

文字列ストリームを使用した怠惰なソリューション:

#include <string>
#include <sstream>

std::istringstream iss(" a b c d e \t f \tg");
std::string w, result;

if (iss >> w) { result += w; }
while (iss >> w) { result += ' ' + w; }

// now use `result`
于 2012-07-20T20:51:14.020 に答える
2

「epur」の意味を定義していませんが、この例では、先頭の(および末尾の)空白を削除し、内部の空白を単一のスペースに置き換えているように見えます。std::replace_if、std::uniqiue、および std::copy_if を組み合わせてこれを行うことができますが、これはかなり複雑であり、データを複数回コピーすることになります。単一のパスをインプレースで実行したい場合は、単純なループがおそらく最適です。

void epur(std::string &s)
{
  bool space = false;
  auto p = s.begin();
  for (auto ch : s)
    if (std::isspace(ch)) {
      space = p != s.begin();
    } else {
      if (space) *p++ = ' ';
      *p++ = ch;
      space = false; }
  s.erase(p, s.end());
}
于 2012-07-20T21:47:24.177 に答える
0

文字列から文字を削除したいようです\t。これを行うには、次のようになっていない文字をコピー\tします。

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

int main() 
{
  std::string s1( "a b c \t d e f \t" );
  std::string s2;

  std::copy_if( std::begin(s1), 
                std::end(s1), 
                std::back_inserter<std::string>(s2),
                [](std::string::value_type c) {
                    return c != '\t';
                } );

  std::cout << "Before: \"" << s1 << "\"\n";
  std::cout << "After: \"" << s2 << "\"\n";
}

出力:

Before: "a b c   d e f  "
After: "a b c  d e f "

文字列からすべての空白を削除する場合は、returnステートメントを次のように置き換えます。

return !std::isspace(c);

isspaceはヘッダーcctypeにあります)

于 2012-07-20T20:49:37.213 に答える