2013-02-03 66 views
10

我嘗試迭代通過char字符串。我試過這樣的:通過字符串迭代字符char通過字符

void print(const string& infix) 
{ 
char &exp = infix.c_str(); 
while(&exp!='\0') 
{ 
     cout<< &exp++ << endl; 
    } 
} 

所以這個函數調用print(「hello」);應該返回:

h 
e 
l 
l 
o 

我嘗試使用我的代碼,但它根本不起作用。順便說一句,參數不是指針。謝謝

+0

參數可能是一個參考,是的,但這樣是'exp' 。順便說一句,'std :: string'已經重載了'operator []',並且它有'begin()'和'end()'函數,並且可以使用免費版本的函數對進行迭代。 – chris

+0

可能重複的[我如何遍歷一個字符串,也知道索引(當前位置)?](http://stackoverflow.com/questions/1315041/how-can-i-iterate-through-a-string-並且還知道該索引當前位置) – jww

+0

可能重複[對於字符串中的每個字符](http://stackoverflow.com/questions/9438209/for-every-character-in-string) – Csq

回答

10
for(unsigned int i = 0; i<infix.length(); i++) { 
    char c = infix[i]; //this is your character 
} 

這就是我做到的。不知道這是否太「慣用」。

+0

@ user1988385,對於打印,即使'std :: cout << infix;'也適用。 – chris

0

std::string::c_str()返回const char*,您不能使用char&來保存它。此外exp爲指針已經,你並不需要參考:如果您使用std::string

void print(const string& infix) 
{ 
    const char *exp = infix.c_str(); 
    while(*exp!='\0') 
    { 
    cout << *exp << endl; 
    exp++; 
    } 
} 
+0

是否有任何理由我們會使用char *而不是for循環(在我的答案中)?我從來沒有確定過,其他人是如何做到這一點的。 –

+0

@DhaivatPandya,不是真的,沒有。使用'const char *'迭代'std :: string'似乎對我毫無意義的努力。 – chris

+0

我會使用迭代器,而不是對原始指針進行操作.... – billz

5

更好地使用iterator雖然:

void print(const string& infix) 
{ 
    for (auto c = infix.begin(); c!=infix.end(); ++c) 
    { 
    std::cout << *c << "\n"; 
    } 
    std::cout << std::endl; 
} 

要解決你的原代碼,嘗試,真的沒有理由這樣做。你可以使用迭代器:

for (auto i = inflix.begin(); i != inflix.end(); ++i) std::cout << *i << '\n'; 

至於你的原代碼,你應該一直使用char*代替char,你並不需要參考。

+0

但是,也許他不僅要複製它?他只是被問到如何逐個字符地遍歷字符串。 –

+0

根據你在做什麼,可能有些東西可以替代'copy'調用,但是,它的工作原理大致相同。 – chris

+0

關於輸出的有趣之處在於,你可以也應該只是'std :: cout << infix;'。但是,需要做其他任何事情,算法或迭代器循環都可以工作。另外,如果已經使用'auto',我會在迭代器循環中使用基於範圍的for循環:p – chris

16

你的代碼需要一個指針,而不是一個參考,但如果使用的是C++編譯器11,所有你需要的是:

void print(const std::string& infix) 
{ 
    for(auto c : infix) 
     std::cout << c << std::endl; 
}