遍历字符串的三种方式:(注意新式for循环)

就以:把字符串“1234”转换为整形1234,为例来说明遍历字符串的三种方式:

①常规方式(下标+operator[])

    #include <iostream>
    #include <string>
    #include <vector>
    #include <list>
    using namespace std;
     
    int StrToInt1(string str)
    {
        int value = 0;
        for (size_t i = 0; i < str.size(); i++)
        {
            value *= 10;
            value += str[i] - '0';
        }
        return value;
    }
     
    int main()
    {
        cout << StrToInt1("1234") << endl;
        system("pause");
        return 0;
    }

②使用迭代器遍历字符串

    #include <iostream>
    #include <string>
    #include <vector>
    #include <list>
    using namespace std;
     
    int StrToInt2(string str)
        {
            //迭代器--在STL中,不破坏封装的情况下去访问容器
        int value = 0;
        string::iterator it = str.begin();//返回第一个位置的迭代器(类似于指针)
        while (it != str.end())//str.end()是最后一个数据的下一个位置
        {
            value *= 10;
            value += (*it - '0');
            it++;
        }
        cout << endl;
     
        vector<int> v;//顺序表的迭代器
        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<int> l;链表的迭代器
        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 << StrToInt2("1234") << endl;
        system("pause");
        return 0;
    }


③新式for循环  (第三种字符串遍历方式源自于c++11)

    #include <iostream>
    #include <string>
    #include <vector>
    #include <list>
    using namespace std;
     
    int StrToInt3(string str)
        {
            int value = 0;
            for (auto ch : str)//ch依次取的是str里面的字符,直到取完为止
            {
                value *= 10;
                value += (ch - '0');
            }
            return value;
        }
     
    int main()
    {
        cout << StrToInt3("1234") << endl;
        system("pause");
        return 0;
    }

需要注意的是:新式for循环的底层是用迭代器实现的
————————————————
版权声明:本文为CSDN博主「qq_42270373」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_42270373/article/details/84589231

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值