0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[初心者向け]C++で文字列から特定の文字を削除する【erase + remove_if + ラムダ式】

Last updated at Posted at 2025-07-17

🏁 はじめに

C++で文字列から特定の文字を削除したい──そんなシーン、意外と多いですよね。

例えば、以下のような操作:

"abcabcABC" から 'a'  'b' を削除  "ccABC"

これをスマートかつ効率的に実現できるのが、

std::remove_if() + std::string::erase() + ラムダ式

の組み合わせです。

🔍 なぜこれが良いのか?

メリット 説明
シンプル C++標準ライブラリだけで完結
高速 std::remove_if() は線形時間で動作
柔軟 ラムダ式で条件変更が容易

🧪 実行可能なサンプルコード

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


int main() {
    std::string str = "abcabcABC";

    // 'a' と 'b' を削除
    str.erase(std::remove_if(str.begin(), str.end(), [](char c) {
        return c == 'a' || c == 'b';
    }), str.end());

    std::cout << str << std::endl; // => ccABC
    return 0;
}

💡 複数文字を削除したいときは?

std::string::find() を使うことで、複数の文字を一気に削除できます。

std::string str = "abcabcABC";
std::string del = "ab"; // 消したい文字の一覧

str.erase(std::remove_if(str.begin(), str.end(), [&del](char c) {
    return del.find(c) != std::string::npos;
}), str.end());

✅ 応用例

std::string del = "abc123"; // 複数文字にも対応

このように del を拡張すれば、柔軟に条件を変えられます。

⚙️ remove_if + erase の仕組み
C++ STLの remove_if は実際に削除はしません。条件に合う要素を末尾に詰めて、その位置を返すだけです。

std::remove_if(...) // 条件に合う要素を末尾に移動
str.erase(...)      // それ以降を削除

📝 まとめ

方法 特徴
erase + remove_if + ラムダ式 C++定番の削除テクニック
findとの併用 複数文字にも対応可能
標準ライブラリのみ 外部依存なし・安全・効率的
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?