gpt4 book ai didi

c++ - 如何遍历字符串并知道索引(当前位置)?

转载 作者:IT老高 更新时间:2023-10-28 13:58:15 26 4
gpt4 key购买 nike

通常在遍历字符串(或任何可枚举对象)时,我们不仅对当前值感兴趣,而且对位置(索引)感兴趣。要通过使用 string::iterator 来实现这一点,我们必须维护一个单独的索引:

string str ("Test string");
string::iterator it;
int index = 0;
for ( it = str.begin() ; it < str.end(); it++ ,index++)
{
cout << index << *it;
}

上面显示的样式似乎并不优于'c-style':

string str ("Test string");
for ( int i = 0 ; i < str.length(); i++)
{
cout << i << str[i] ;
}

在 Ruby 中,我们可以优雅地获取内容和索引:

"hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" }

那么,在 C++ 中迭代可枚举对象并跟踪当前索引的最佳做法是什么?

最佳答案

像这样:


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;

关于c++ - 如何遍历字符串并知道索引(当前位置)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1315041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com