1. 程式人生 > >【c++】遍歷字串的三種方式

【c++】遍歷字串的三種方式

就以:把字串“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迴圈的底層是用迭代器實現的