相关疑难解决方法(0)

对于字符串中的每个字符

如何在C++中对字符串中的每个字符执行for循环?

c++ loops for-loop character

208
推荐指数
6
解决办法
37万
查看次数

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

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

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

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

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

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

"hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" }
Run Code Online (Sandbox Code Playgroud)

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

c++ string iterator

54
推荐指数
4
解决办法
15万
查看次数

标签 统计

c++ ×2

character ×1

for-loop ×1

iterator ×1

loops ×1

string ×1