提取字符串中的数字

题目:输入一个字符串,有数字和非数字如: “313wrw.13341231se][‘w23’ww” 要求将连续的数字做为一个整数,如313,1334,将其存到一个数组里,并统计有多少个,最后打印出来。

思路:

  • 题目要求连续的数字作为一个整数,那么从后面遍历字符串方便处理高位的问题;
  • 设置一个倍数flag,若为连续数字则倍数*10,遇到字符则倍数清零;
  • 字符串里有多组数字的时候还要判断什么时候数组后移,若数字的前一个字符不是数字则数组后移同时倍数清零。
Created with Raphaël 2.1.0 Start 输入字符 是否是数字? 数字乘以倍数 后一位是数字? 倍数清零且数组移动 倍数清零 yes no yes no
#include 
#include 
#include 
#define Max_num 1000
int main()
{
    char str[Max_num];
    while (cin >> str)
    {
        int num[Max_num] = { 0 };
        int cnt = 0;
        int beishu = 0;
        for (int i = strlen(str) - 1;i >= 0;i--)//从后面遍历方便计算更高位
        {
            while (isdigit(str[i]))                 
            {
                num[cnt] += (str[i] - '0') * pow(10, beishu);  //
                beishu++;
                i--;
                if (i == -1)
                {
                    cnt++;
                    break;
                }
            }
            if (i >= 0)
            {
                if (!isdigit(str[i]) && isdigit(str[i + 1]))  //如果str[i]不是数字且str[i+1]是数字则倍数清零,数字数组后移
                {
                    beishu = 0;
                    cnt++;
                }
                else if (!isdigit(str[i]))  //如果都是字符的话数组不移动只清零
                    beishu = 0;
            }
        }
        cout << "有 " << cnt << " 个数字\n";
        for (int i = cnt - 1;i >= 0;i--)
        {
            cout << num[i] << endl;
        }
    }
    return 0;
}

你可能感兴趣的:(c++学习)