把字符串“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;
}