从字符中提取数字总结的方法

参照网站:https://blog.csdn.net/hhyvs111/article/details/78670530

                  https://blog.csdn.net/xiaofei2010/article/details/7460831

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

思路:

  • 题目要求连续的数字作为一个整数,那么从后面遍历字符串方便处理高位的问题;
  • 设置一个倍数flag,若为连续数字则倍数*10,遇到字符则倍数清零;
  • 字符串里有多组数字的时候还要判断什么时候数组后移,若数字的前一个字符不是数字则数组后移同时倍数清零。
#include <iostream>
#include <cctype>
#include <cstring>
#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;
}

上面是一种方法

还有一种从字符串中提取整数

可以采用字符串流

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
	string str="234 567 0abc123 ?789";
	istringstream is(str);
	int i;
	char ch;
	cout<<"输出字符串中的数字:"<<endl;
	while (is>>ch)
	{
		if (ch>='0'&&ch<='9')
		{
			is.putback(ch);//将ch放回到输入流中,这样后面用is>>i可以完整的读入数字
			is>>i;
			cout<<" i: "<<i<<endl<<endl;
		}
	}
	system("pause");
	return 0;
}

第三种方式

可以种sscanf来实现

详细sscanf的用法见下面网站

https://www.cnblogs.com/hejing-swust/p/7793958.html

猜你喜欢

转载自blog.csdn.net/qq_40570748/article/details/81165606
今日推荐