[C++] 文字から空白取り除く方法 (std::string)

1 min read
hiroweb developer

空白を取り除く方法

C++で文字列から空白を取り除くには、以下のようにしてstd::stringのメンバー関数であるeraseremove_ifを利用する。

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

int main(){
    std::string str = "a b c d e f g";
  str.erase(std::remove_if(str.begin(), str.end(), std::isspace), str.end());
    std::cout << str << std::endl;

    return 0;
}

このコードを実行すると、以下の出力が出力される。

abcdefg

このコードでは、std::isspaceという標準ライブラリ関数を使用して、文字列中の空白文字を特定する。std::remove_ifは、条件を満たす要素を削除し、削除された場所の後ろに残った要素の新しい終端を返す。その後、std::stringのメンバー関数であるeraseを使用して、削除された部分文字列を削除する。

このようにして、std::stringのメンバー関数を使用して、C++で文字列から空白を取り除くことができる。