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

c++, iterator, string

Solution

I've never heard of a best practice for this specific question. However, one best practice in general is to use the simplest solution that solves the problem. In this case the array-style access (or c-style if you want to call it that) is the simplest way to iterate while having the index value available. So I would certainly recommend that way.

Problem

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?

Original source

Related problems