C++ :String的三种遍历方式(下标+operator[] 、迭代器、C++11新式for循环)

String的三种遍历方式

string的本质:底层是一个字符串的数组,支持动态增长

把字符串“1234”转换为整形1234

<1>下标+operator[ ] (像数组一样使用)

数组遍历用[]
把"1234"转换成整形

#include <iostream>
#include <string>   //字符串

int StrToIntl(string str)
{
    int value = 0;
    for (size_t i = 0; i < str.size(); ++i)
    {
        //实现打印
        //cout << str[i] << " ";
        //cout << str.operator[](i) << " ";  //等价上一行 operator[]是函数;(i)是参数;访问底层数组的第i个字符
        value *= 10;
        value += str[i] - '0';   //运算符重载,函数调用;十进制数值 = 字符串的ASCll码值-‘0’
    }
    return value;
}

int main()
{
    cout << StrToInt1("1234") << endl;
    system("pause");
    return 0;
}

<2>stl中的迭代器(想象指针)

#include <iostream>
#include <string>   //字符串
#include <vector>   //顺序表(数组)
#include <list>     //链表

int StrToInt2(string str)
{
    int value = 0;
    //在stl中的迭代器(可想象成指针):不破坏封装的情况下去访问容器
    string::iterator it = str.begin();   //1234
    while (it != str.end())
    {
        value *= 10;
        value += (*it - '0');
        ++it;
    }

    //vector迭代器
    
    //vector<int> v;               //1 2 3
    //v.push_back(1);
    //v.push_back(2);
    //v.push_back(3);
    //vector<int>::iterator vit = v.begin();
    //while (vit != v.end())
    //{
    //  cout << *vit << " ";
    //  ++vit;
    //}
    //cout << endl;

    //list迭代器
    
    //list<int> l;                  //10 20 30
    //l.push_back(10);
    //l.push_back(20);
    //l.push_back(30);
    //list<int>::iterator lit = l.begin();
    //while (lit != l.end())
    //{
    //  cout << *lit << " ";
    //  ++lit;
    //}
    //cout << endl;

    return value;
}

int main()
{
    cout << StrToInt1("1234") << endl;
    system("pause");
    return 0;
}

迭代器使用统一的方式遍历,并且屏蔽了底层的细节

å¨è¿éæå¥å¾çæè¿°

<3>C++11新式for循环(底层实现是迭代器;auto自动推到类型,C++11支持)

#include <iostream>
#include <string>  
#include <vector>  
#include <list>     

int StrToInt3(string str)
{
    int value = 0;
    //C++11
    for (auto ch : str)
    {
        value *= 10;
        value += (ch - '0');  //ch表示:依次取str里的字符,直到取完为止
    }
    return value;
}

int main()
{
    test_string3();
    system("pause");
    return 0;
}
发布了103 篇原创文章 · 获赞 54 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/u012903992/article/details/103238053