Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate through a string and also know the index (current position)?

Often when iterating through a string (or any enumerable object), we are not only interested in the current value, but also the position (index). To accomplish this by using string::iterator we have to maintain a separate index:

string str ("Test string"); string::iterator it; int index = 0; for ( it = str.begin() ; it < str.end(); it++ ,index++) {     cout << index << *it; } 

The style shown above does not seem superior to the 'c-style':

string str ("Test string"); for ( int i = 0 ; i < str.length(); i++) {     cout << i << str[i] ; } 

In Ruby, we can get both content and index in a elegant way:

"hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" } 

So, what is the best practice in C++ to iterate through an enumerable object and also keep track of the current index?

like image 242
pierrotlefou Avatar asked Aug 22 '09 03:08

pierrotlefou


People also ask

Can you iterate through a string?

Strings are inherently iterable, which means that iteration over a string gives each character as output. In the above example, we can directly access each character in the string using the iterator i .

How do you find a for loop in a string?

For loops with strings usually start at 0 and use the string's length() for the ending condition to step through the string character by character. String s = "example"; // loop through the string from 0 to length for(int i=0; i < s. length(); i++) { String ithLetter = s.

How do you go through a character in a string C++?

Program to loop on every character in string in C++ To loop on each character, we can use loops starting from 0 to (string length – 1). For accessing the character we can either use subscript operator "[ ]" or at() function of string object.


1 Answers

Like this:

     std::string s("Test string");     std::string::iterator it = s.begin();      //Use the iterator...     ++it;     //...      std::cout << "index is: " << std::distance(s.begin(), it) << std::endl; 
like image 124
Leandro T. C. Melo Avatar answered Sep 26 '22 17:09

Leandro T. C. Melo