字符串中數字子串的求和

#include <iostream>
#include <string>
using namespace std;
int numSum(string str)
{
    int res = 0;
    int num = 0;
    bool posi = true;
    int cur = 0;
    for(int i = 0; i < str.size(); ++i)
    {
        cur = str[i] - '0';
        if(cur < 0 || cur > 9)
        {
            res += num;
            num = 0;
            if(str[i] == '-')
            {
                if(i - 1 > -1 && str[i - 1] == '-')
                    posi = !posi;
                else
                    posi = false;
                } else {
                    posi = true;
                }
        } else {
            num = num * 10 + (posi ? cur : -cur);
        }
    }
    res += num;
    return res;
}
int main()
{
    string str = "A-1B--2C-D6E";
    cout << numSum(str) << endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章