在C++中遍历字符串(容器类)的三种方式

把字符串“1234”转换为整形1234,为例来说明遍历字符串的三种方式:
1.常规方式(下标+operator[]),类似数组方式

#include <iostream>
#include <string>
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;
}

2.使用迭代器方法,和STL中的vector,map,list等容器一样使用迭代器遍历

#include <iostream>
#include <string>
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++;
    }
    return value;
}
 
int main()
{
    cout << StrToInt2("1234") << endl;
    system("pause");
    return 0;
}

3.新式for循环。对于vector等容器类也可以使用该方式遍历其中的元素

#include <iostream>
#include <string>
#include <vector>
#include <list>
using namespace std;
 
int StrToInt3(string str)
    {
        int value = 0;
        for (auto ch : str)//ch依次取的是str里面的字符,直到取完为止
        //也可以写成for(const char& ch : str),因为字符串每个元素都是字符,所以用char
        {
            value *= 10;
            value += (ch - '0');
        }
        return value;
    }
 
int main()
{
    cout << StrToInt3("1234") << endl;
    system("pause");
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值