2013-10-28 33 views
0

我有以下形式的字符串在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實現相同的有效方法?

+0

它是如何低效也許一些代碼?請記住,當從中間的字符串中刪除一個字符時,意味着所有連續字符都必須移回一個字符,您必須使用臨時字符串來確保不會發生這種情況。 – Xonar

+0

這是C++,請刪除C標籤。 – clcto

+0

從主題和標籤中刪除'C'。 'C'沒有'string'類型,當你說'C++/C'字符串時,人們假設你的意思是nul結尾的字符數組。 – kfsone

回答

7

使用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行爲取決於當前的語言環境。

+2

刪除單個字符。 – jrok

+0

['std :: ispunct'](http://en.cppreference.com/w/cpp/locale/ispunct)怎麼樣? – 0x499602D2

+0

我不知道爲什麼,但它給了我錯誤:沒有匹配的函數調用'remove_if(std :: basic_string :: iterator,std :: –

2

工作的代碼示例: 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; 
}