2010-01-13 94 views
5

我在函數中有一個const char * const字符串。 我想用它來比較字符串中的元素。比較字符串迭代器到字符指針

我想遍歷字符串,然後與char *進行比較。

#include <iostream> 
#include <string> 
#include <cstring> 

using namespace std; 

int main() 
{ 

    const char * const pc = "ABC"; 
    string s = "Test ABC Strings"; 

    string::iterator i; 

    for (i = s.begin(); i != s.end(); ++i) 
    { 
    if ((*i).compare(pc) == 0) 
    { 
     cout << "found" << endl; 
    } 
    } 

如何解決一個char *來解決字符串迭代器?

謝謝..

回答

15

std::string::find

const char* bar = "bar"; 
std::string s = "foo bar"; 

if (s.find(bar) != std::string::npos) 
    cout << "found!"; 
+0

衛生署,我沒想到那麼遠的。你說得對,使用'find'比嘗試自己重新實現要好得多。 +1 – jalf 2010-01-13 16:58:23

+0

這個作品,謝謝! – donalmg 2010-01-14 13:48:35

5
std::string::iterator it; 
char* c; 
if (&*it == c) 

解引用一個迭代產生一個參考指向的對象。所以解引用給你一個指向對象的指針。

編輯
當然,這是不是一個更好的方法是完全省略了比較,並依靠已經存在於你想要做什麼的find功能密切相關。

1

不完全回答你的問題,但它看起來像你可能與std::string::find方法更好。

類似的東西:

const char * const pc = "ABC"; 
string s = "Test ABC Strings"; 
size_t pos = s.find(pc);