2011-03-24 120 views
8

我試着做了一個字符串迭代循環內的if語句,但無法弄清楚如何獲得當前字符if語句:C++字符串迭代器

for (std::string::iterator i=buffer.end()-1; i>=buffer.begin(); --i) { 
    if (!isalpha(*i) && !isdigit(*i)) { 
     if(i != "-") { // obviously this is wrong 
      buffer.erase(i); 
     } 
    } 
} 

燦有人幫我獲得當前角色,這樣我可以做一些額外的if語句?

+0

你爲什麼標記該C? – GManNickG 2011-03-24 17:08:46

+0

你真的不需要isalpha和isdigit檢查你是否要檢查後面的特定字符 – AJG85 2011-03-24 17:17:59

回答

19

我無法弄清楚如何獲得當前字符

你做在這裏兩次:

if (!isalpha(*i) && !isdigit(*i)) 

當你解引用一個迭代器(*i),你得到的元素它指出的。

"-" 

這是一個字符串文字,而不是字符。字符常量使用單引號,例如'-'

for (std::string::iterator i=buffer.end()-1; i>=buffer.begin(); --i) 

這將是非常簡單的反向迭代器:

for (std::string::reverse_iterator i = buffer.rbegin(); i != buffer.rend(); ++i) 
+1

if((* i)!=' - '))如果您需要更多的澄清 – Pepe 2011-03-24 17:10:02

+0

@ P.R .:對'' - - ''很好的理解。 – 2011-03-24 17:11:12

+0

工作,謝謝! – Joe 2011-03-24 17:13:48

2

爲了獲得字符只是說*i,但這是遠遠不夠的。你的循環是不合法的,因爲它不允許在begin之前遞減。您應該使用反向迭代器或remove_if算法。

1

你在上面的if聲明的正上方:i是一個迭代器,所以*i給出了迭代器引用的字符。

請注意,如果您要向後遍歷集合,通常使用reverse_iteratorrbeginrend更容易。我可能會使用預先打包的算法。

3
if(i != "-") 

應該

if(*i != '-') 
2

其他答案已經解決了,你有特別的問題,但你應該知道,有解決您最實際的問題不同的方法:即fullfill條件擦除元素。可與刪除迎刃而解/擦除成語:

// C++0x enabled compiler 
str.erase( 
    std::remove_if(str.begin(), str.end(), 
        [](char ch) { return !isalpha(ch) && !isdigit(ch) && ch != '-' }), 
    str.end()); 

雖然這可能看起來很麻煩,首先,當你看到它了幾次就不再是令人驚奇的,而且它是一個有效的從矢量或字符串中刪除元素的方法。

如果你的編譯器沒有拉姆達支持,那麼你可以創建一個仿函數,並把它作爲第三個參數remove_if

// at namespace level, sadly c++03 does not allow you to use local classes in templates 
struct mycondition { 
    bool operator()(char ch) const { 
     return !isalpha(ch) && !isdigit(ch) && ch != '-'; 
    } 
}; 
// call: 
str.erase( 
    std::remove_if(str.begin(), str.end(), mycondition()), 
    str.end()); 
+0

不敢相信我是第一個贊成這個! :-) – 2016-12-14 09:23:25