ブーストを使用せずに std::string を作成するための最良の方法と最も簡単な方法を知っています。
たとえば、この文字列を変換する方法
" a b c d e '\t' f '\t'g"
の
"a b c d e f g"
'\t' が通常の集計であると仮定します。
ありがとう。
文字列ストリームを使用した怠惰なソリューション:
#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`
「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());
}
文字列から文字を削除したいようです\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にあります)