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

前端 未结 7 718
小蘑菇
小蘑菇 2020-12-14 14:27

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

7条回答
  •  悲哀的现实
    2020-12-14 15:11

    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;
    

提交回复
热议问题