2014-01-07 129 views
0

我對這個論壇和C++非常新穎。所以請原諒我的疑惑/問題。我正在閱讀std::string。我知道我可以使用at[int]運營商訪問元素。我有2個問題:閱讀std :: string,從std :: string中刪除所有特殊字符

1)刪除或字符串刪除所有特殊字符(包括空格)

2)只讀首次從該字符串

爲1),我是4個字符或字母檢查std::erasestd::remove_if,但我需要消除所有我的意思是特殊字符和空格。這意味着我需要包含所有的條件,如isspace()/isalpha()等等。有沒有一種方法可以一次全部刪除?對於2),我可以像數組那樣訪問字符串,我的意思是string [0],string [1],string [2],string [3]。但我不能添加到單個字符串?

請讓我知道我該怎麼做到這一點?

+0

哪些字符是「特殊字符」? – zch

+0

是的,我的意思是所有在我們的鍵盤的第二行。 – johnkeere

回答

3

爲了得到第四個大字:

std::string first4=str.substr(0, 4); 

要刪除任何isspace判斷,因而isalpha謂詞(雖然我覺得我誤解了,在這裏,你的意思isspace判斷,而不是因而isalpha ??):

str.erase(std::remove_if(str.begin(), str.end(), 
    [](char c) { return std::isspace(c) || std::isalpha(c); }), 
    str.end()); 

可以使用op+=附加到字符串。例如:

str+="hello"; 
str+='c'; 
0

要刪除所有特殊字符,爲什麼不能讓像一個方法,以便:

bool isLegal(char c) 
{ 
    char legal[] = {'a', 'A', 'b','B' /*..and so on*/}; 
    int len = sizeof(legal)/sizeof(char); 

    for (int i = 0; i < len; i++) 
    if (c == legal[i]) 
     return true; 
    return false; 
} 

,然後就重複槽字符串,並刪除字符不合法?

0

對於1:std :: remove_if將刪除給定謂詞返回true的所有元素。您提供了謂詞函數對象,只要它從容器(char)中取出一個元素並返回一個布爾值,它就可以是您想要的任何對象。

所以,你可以寫一個函數,例如:

bool IsNotLegal(const char & stringElement); 

,或者你可以把它寫成一個lambda函數,然後你就可以將它傳遞到std ::的remove_if從滿足字符串中刪除你的一切條件1通。

std::string myString{"This is my string."}; 
std::remove_if(std::begin(myString), std::end(myString),[](const char & element) 
{ 
    return std::isspace(element) && //any other conditions such as your own IsSpecial(); 
}); 
// now myString has become "Thisismystring."