2013-05-28 119 views
1

我希望能夠遍歷C++字符串中的每個字符。最簡單的方法是什麼?先將它轉換爲C字符串?我還沒有真正能夠得到它的工作的任何方式,但這裏是我試過到目前爲止:索引C++字符串的最簡單方法是什麼?

string word = "Foobar"; 
for (int i=0; i<word.length(); ++i) { 
    cout << word.data()[i] << endl; 
} 
+7

'operator []'被重載爲'std :: string'。所以簡單地說'cout << word [i] << endl;'。 –

回答

5

您可以直接在字符串上使用operator[]。它超載。

string word = "Foobar"; 
for (size_t i=0; i<word.length(); ++i) { 
    cout << word[i] << endl; 
} 
2

std::string公開隨機訪問迭代器,所以你可以用這些來的每一個字符迭代器在字符串中。

2

整個字符串迭代最簡單的方法是使用基於for循環一個C++ 11範圍:

for (auto c : word) 
{ 
    std::cout << c << std::endl; 
} 

否則,可以通過operator[]訪問單個元件,你會陣列,或使用迭代器:

for (std::string::size_type i = 0, size = word.size(); i < size; ++i) 
{ 
    std::cout << word[i] << std::endl; 
} 

for (auto i = word.cbegin(), end = word.cend(); i != end; ++i) 
{ 
    std::cout << *i << std::endl; 
} 
+0

提醒:這種表示法是C++ 11語法,不適用於C++ x03 –

+0

在第二個循環中,auto必須爲'i'和'size'推導出相同的類型。但'i'是用unsigned int和'size'與std :: string :: size_type(幾乎可以肯定是一個'std :: size_t')初始化的。這些可能是不同的類型(例如,在64位Windows上是LLP64而不是LP64),從而導致編譯器錯誤。 –

+0

@AdrianMcCarthy好點。它在我測試過的一個平臺上工作。我會解決這個問題。 – juanchopanza

2

你應該有什麼工作(對於合理的短字符串);雖然你可以訪問每個字符作爲word[i]而不用弄亂指針。

迂迴地,你應該使用string::size_typesize_t而不是int

你可以使用一個迭代器:

for (auto it = word.begin(); it = word.end(); ++it) { 
    cout << *it << endl; 
} 

(早於C++ 11,你必須給類型名稱string::iteratorstring::const_iterator而非auto)。

在C++ 11,你可以遍歷一個範圍:

for (char ch : word) { 
    cout << ch << endl; 
} 

,或者您可以使用for_each與拉姆達:

for_each(word.begin(), word.end(), [](char ch){cout << ch << endl;}); 
5

您應該使用迭代器。此方法適用於大多數STL的容器。

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string str("Hello world !"); 

    for (std::string::iterator it = str.begin(); it != str.end(); ++it) 
    std::cout << *it << std::endl;            
} 
0

最簡單的方式做到這一點,因爲其他人已經指出的那樣,是使用[]操作,在String類重載。

string word = "Foobar"; 
for (int i=0; i<word.length(); ++i) { 
    cout << word[ i ] << endl; 
} 

如果你已經知道如何遍歷C字符串,然後有一個機制,類似於C的指針,你可以使用,這將是很多更好的性能。

string word =「Foobar」;
爲(字符串::爲const_iterator它= word.begin();!它= word.end(); ++它) { COUT < < *它< < ENDL; }

你有常量迭代器和常規迭代器。當你計劃改變它們指向的數據將迭代時,將使用後者。前者適用於只讀操作,如控制檯轉儲。

string word = "Foobar"; 
for (string::iterator it = word.begin(); it != word.end(); ++it) 
{ 
    (*it)++; 
} 

通過上面的代碼,您將使用下一個字符「加密」您的單詞。

最後,你總是想回到C指針的可能性:

string word = "Foobar"; 
const char * ptr = word.c_str(); 

for (; *ptr != 0; ++ptr) 
{ 
    (*ptr)++; 
} 

希望這有助於。

相關問題