2015-10-23 114 views
0

我有這個代碼的問題,我試圖驗證一個字母是否在一個單詞中,但由於某些原因它不會讓我把==沒有運算符「==」匹配這些操作數字符串

#include <string> 
#include <iostream> 
using namespace std; 

bool Verification(string a, string b) 
{ 
    bool VF = false; 
    for (int i = 0; i < a.size(); i++) 
    { 
     if (a[i] == b) //Here is the problem 
     { 
      VF = true; 
     } 

    } 
    return VF; 
} 
+0

您的意思是? 'if(a [i] == b [i])' –

+0

正如錯誤所述,沒有'operator =='可以比較'char'和'string' – Praetorian

+0

爲什麼要這樣做? –

回答

4

a是一個字符串和b是一個字符串。
a[i]char。你比較charstring - 顯然,它不會工作。

如果你想檢查是否(即char)在句子(即string)存在,就可以實現的功能是這樣的:

bool Verification(string a, char b) // <-- notice: b is char 
{ 
    bool VF = false; 
    for (int i = 0; i < a.size(); i++) 
    { 
     if (a[i] == b) 
     { 
      VF = true; 
     } 
    } 
    return VF; 
}  

// Usage: 
Verification("abc", 'a'); // <-- notice: quotes are double for string and single for char 

其實,有一種方法string::find,它可以幫助你找到stringchar在另一個string 的occurence您可以替換代碼:

#include <string> 
#include <iostream> 
using namespace std; 

bool Verification(string a, char b) 
{ 
    return a.find(b) != string::npos; 
}  
+0

好的,謝謝。但是當我有[我]時,我的字符串是如何變成字符的? –

+3

@JonathanBouchard任何語言(f.i.,英文)** word **由**字母**組成。因此,在C++和許多其他語言中** string **由** char ** s組成。你已經應用的['string :: operator []'](http://www.cplusplus.com/reference/string/string/operator [] /)返回** char **。如果你有**字(字符串)** **蘋果**,那麼第5個**字母(char)**是'e'。 –

+0

哈哈哈,好的謝謝 –

相關問題