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

前端 未结 7 720
小蘑菇
小蘑菇 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:09

    For strings, you can use string.c_str() which will return you a const char*, which can be treated as an array, example:

    const char* strdata = str.c_str();
    
    for (int i = 0; i < str.length(); ++i)
        cout << i << strdata[i];
    

提交回复
热议问题