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?
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 .
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With