C++ では、次のように簡単に変換できます。
この std::string
\t\tHELLO WORLD\r\nHELLO\t\nWORLD \t
の中へ:
HELLOWORLDHELLOWORLD
C++ では、次のように簡単に変換できます。
この std::string
\t\tHELLO WORLD\r\nHELLO\t\nWORLD \t
の中へ:
HELLOWORLDHELLOWORLD
std::remove_if
との単純な組み合わせstd::string::erase
。
完全に安全ではないバージョン
s.erase( std::remove_if( s.begin(), s.end(), ::isspace ), s.end() );
より安全なバージョンに置き換える::isspace
には
std::bind( std::isspace<char>, _1, std::locale::classic() )
(関連するすべてのヘッダーを含めます)
代替の文字タイプで動作するバージョンの場合は、テンプレート化された文字タイプに置き換えます<char>
。<ElementType>
もちろん、ロケールを別のものに置き換えることもできます。これを行う場合は、ロケール ファセットを何度も再作成して非効率にならないように注意してください。
C++11 では、より安全なバージョンをラムダにすることができます:
[]( char ch ) { return std::isspace<char>( ch, std::locale::classic() ); }
C++03の場合
struct RemoveDelimiter
{
bool operator()(char c)
{
return (c =='\r' || c =='\t' || c == ' ' || c == '\n');
}
};
std::string s("\t\tHELLO WORLD\r\nHELLO\t\nWORLD \t");
s.erase( std::remove_if( s.begin(), s.end(), RemoveDelimiter()), s.end());
または、C++11 ラムダを使用します
s.erase(std::remove_if( s.begin(), s.end(),
[](char c){ return (c =='\r' || c =='\t' || c == ' ' || c == '\n');}), s.end() );
PS。消去削除イディオムが使用されます
C++11 では、std::bind を使用する代わりにラムダを使用できます。
str.erase(
std::remove_if(str.begin(), str.end(),
[](char c) -> bool
{
return std::isspace<char>(c, std::locale::classic());
}),
str.end());
c++11
std::string input = "\t\tHELLO WORLD\r\nHELLO\t\nWORLD \t";
auto rs = std::regex_replace(input,std::regex("\\s+"), "");
std::cout << rs << std::endl;
/tmp ❮❮❮ ./play
HELLOWORLDHELLOWORLD
Boost.Algorithmを使用できますerase_all
#include <boost/algorithm/string/erase.hpp>
#include <iostream>
#include <string>
int main()
{
std::string s = "Hello World!";
// or the more expensive one-liner in case your string is const
// std::cout << boost::algorithm::erase_all_copy(s, " ") << "\n";
boost::algorithm::erase_all(s, " ");
std::cout << s << "\n";
}
注:コメントに記載されているように:(trim_copy
またはそのいとこtrim_copy_left
およびtrim_copy_right
)は、文字列の最初と最後から空白のみを削除します。
文字ごとにステップスルーして使用すると、正常に機能するstring::erase()
はずです。
void removeWhitespace(std::string& str) {
for (size_t i = 0; i < str.length(); i++) {
if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t') {
str.erase(i, 1);
i--;
}
}
}