在包含数字和字母的字符串中,提取所有数字并组成一个数

思路:利用ASCII中“0-9”,小写字母、大写字母的顺序,实现。

代码:`

#include "iostream"
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>  //opencv申明
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2/opencv.hpp>
#include < string>

using namespace std;
using namespace cv;

int main()
{
	   string s ;
	   cin>>s;
	   int len =s.length();  //.length   表示字符串的长度
	   int a,b,//用来循环扫描字符串
		   bit,//在一个字符串中,对一个外形是数字的字符,把这样的字符转化成数字,存与bit中
		   num;//最终存放提取出的数字
	   int flag=0;//判断字符串中是否有数字
	   cout<<"字符串中的数字有:"<<endl;
	   for(a=0;a<len;a++)
	   {
	    if(s[a]>='0'&&s[a]<='9')//过滤掉外形是非数字的字符
		{
		  flag++;
		  b=a;
		  num=0;//num每次循环的初值置为0
		  while(b<len&&s[b]>='0'&&s[b]<='9')
		  {
             bit=s[b]-'0';
			 num=num*10+bit;
			 b++;
		  }
		  cout<<num<<endl;
		  a=b;
		}
	   }
    if(flag==0)
	cout<<"字符串中无数字"<<endl;
	system("pause");
}`

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43197380/article/details/88679800