簡體   English   中英

刪除C ++字符串中的字符

[英]deleting characters in C++ string

我在C ++中具有以下形式的字符串

   string variable1="This is stackoverflow \"Here we go "1234" \u1234 ABC";

現在,在此字符串中,我要刪除除字母(從a到b,以及A到B)和數字之外的所有字符。 這樣我的輸出就變成

   variable1="This is stackoverflow Here we go 1234 u1234 ABC";

我嘗試使用指針檢查每個字符,但發現效率很低。 有沒有一種有效的方法可以使用C ++ / C實現相同的目標?

使用std::remove_if

#include <algorithm>
#include <cctype>

variable1.erase(
    std::remove_if(
        variable1.begin(),
        variable1.end(),
        [] (char c) { return !std::isalnum(c) && !std::isspace(c); }
    ),
    variable1.end()
);

注意, std::isalnumstd::isspace的行為取決於當前的語言環境。

工作代碼示例: http : //ideone.com/5jxPR5

bool predicate(char ch)
    {
     return !std::isalnum(ch);
    }

int main() {
    // your code goes here


    std::string str = "This is stackoverflow Here we go1234 1234 ABC";

    str.erase(std::remove_if(str.begin(), str.end(), predicate), str.end());
    cout<<str;
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM