C++ 如何遍历字符串并知道索引(当前位置)?
通常在遍历字符串(或任何可枚举对象)时,我们不仅对当前值感兴趣,还对位置(索引)感兴趣。要通过使用C++ 如何遍历字符串并知道索引(当前位置)?,c++,string,iterator,C++,String,Iterator,通常在遍历字符串(或任何可枚举对象)时,我们不仅对当前值感兴趣,还对位置(索引)感兴趣。要通过使用string::iterator实现这一点,我们必须维护一个单独的索引: string str ("Test string"); string::iterator it; int index = 0; for ( it = str.begin() ; it < str.end(); it++ ,index++) { cout << index << *it; }
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++中最好的实践是通过一个枚举对象迭代并跟踪当前索引? 如下:
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;
std::字符串s(“测试字符串”);
std::string::iterator it=s.begin();
//使用迭代器。。。
++它;
//...
std::cout对于字符串,可以使用string.c_str()
返回常量char*,可以将其视为数组,例如:
const char* strdata = str.c_str();
for (int i = 0; i < str.length(); ++i)
cout << i << strdata[i];
const char*strdata=str.c_str();
对于(int i=0;i cout良好实践应基于可读性,例如:
string str ("Test string");
for (int index = 0, auto it = str.begin(); it < str.end(); ++it)
cout << index++ << *it;
string str(“测试字符串”);
对于(int index=0,auto it=str.begin();it cout您可以使用前面提到的标准STL函数距离
index = std::distance(s.begin(), it);
此外,您还可以使用类似c的接口访问字符串和其他一些容器:
for (i=0;i<string1.length();i++) string1[i];
for(i=0;i我从来没有听说过针对这个特定问题的最佳实践。但是,一般来说,一个最佳实践是使用最简单的解决方案来解决问题。在这种情况下,数组样式的访问(或者c样式,如果你想这样称呼它的话)是在索引值可用的情况下进行迭代的最简单方法。因此,我当然会推荐这种方法。我会使用it-str.begin()
在这种特殊情况下,std::distance和运算符-是相同的。但如果容器将更改为没有随机访问的内容,则std::distance将递增第一个参数,直到到达第二个参数,从而给出线性时间和运算符-将不会编译。
就我个人而言,我更喜欢第二种行为——最好在算法从O(n)变成O(n^2)时得到通知。因为std::distance
对于随机访问迭代器来说只是常数时间,我可能更喜欢显式迭代器算法。
此外,由于我们在这里编写C++代码,所以我相信C++风格的解决方案比C风格的方法更可取。
string str{"Test string"};
auto begin = str.begin();
for (auto it = str.begin(), end = str.end(); it != end; ++it)
{
cout << it - begin << *it;
}
string str{“Test string”};
自动开始=str.begin();
for(auto it=str.begin(),end=str.end();it!=end;++it)
{
顺便说一句,在我的实现中,索引的工作速度比迭代器快得多(5倍或更多)。这个问题与我自己的问题类似,所以我想在这里问一下,您如何将stardata[I]的值与“”?有没有办法将其转换为字符?我之前的编辑是正确的,@Alex Reynolds。请检查和。举个例子就好了:P@NickHall他以OP问题中的第二段代码为例。注意第二段代码!str.length()是std::string::size\u类型,所以您需要用std::string::size\u类型声明变量i,否则编译器会给您不必要的警告。
string str ("Test string");
int index = 0;
for (auto it = str.begin() ; it < str.end(); ++it, ++index)
cout << index << *it;
index = std::distance(s.begin(), it);
for (i=0;i<string1.length();i++) string1[i];
string str{"Test string"};
auto begin = str.begin();
for (auto it = str.begin(), end = str.end(); it != end; ++it)
{
cout << it - begin << *it;
}