title: How can I iterate through a string and also know the index (current position)?
body: <p>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 <code>string::iterator</code> we have to maintain a separate index:</p>
  
  <pre><code>string str ("Test string");
  string::iterator it;
  int index = 0;
  for ( it = str.begin() ; it &lt; str.end(); it++ ,index++)
  {
      cout &lt;&lt; index &lt;&lt; *it;
  }
  </code></pre>
  
  <p>The style shown above does not seem superior to the 'c-style':</p>
  
  <pre><code>string str ("Test string");
  for ( int i = 0 ; i &lt; str.length(); i++)
  {
      cout &lt;&lt; i &lt;&lt; str[i] ;
  }
  </code></pre>
  
  <p>In Ruby, we can get both content and index in a elegant way:</p>
  
  <pre><code>"hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" }
  </code></pre>
  
  <p>So, what is the best practice in C++ to iterate through an enumerable object and also keep track of the current index?</p>