C language: extract the number in the string

blogging for the first time 

When doing homework, there is a question that requires counting the numbers in the string

For example, "12s133 358-76vh9", extract each digit and convert it into an integer:

12、133、358、76、9

Logical idea: Traverse the array, judge whether it should start reading numbers and end reading by detecting whether it is at the junction of digital characters or digital characters and other characters, and analogize the rise and fall of potential.

code show as below:

#include<stdio.h>
#include<string.h>
#include<math.h>

int main()
{
	char a[20];
	printf("字符串:");
	gets(a);

	int len=strlen(a),i,j,count=0,wei[20],num[10]={0},times=0;
	bool ctoi=0,befctoi=0;
	for(i=0;i<len+1;i++)
	{
		if(a[i]>='0'&&a[i]<='9')
		{
			ctoi=1;
		}
		else
		{
			ctoi=0;
		}
		if(befctoi==0&&ctoi==1)//上升沿
		{
			wei[count]=a[i]-'0';
			befctoi=1;
			count++;
		}
		else if(befctoi==1&&ctoi==1)//高位
		{
			wei[count]=a[i]-'0';
			count++;
		}
		else if(befctoi==1&&ctoi==0)//下降沿
		{
			for(j=0;j<count;j++)
			{
				num[times]+=wei[j]*pow(10,count-j-1);
			}
			times++;
			befctoi=0;
			count=0;
		}
	}

	printf("%d个数\n",times);
	for(i=0;i<times;i++)
	{
		printf("a[%d]=%d\n",i,num[i]);
	}

	return 0;
}

The effect is as shown in the figure: 

 

Guess you like

Origin blog.csdn.net/m0_54346043/article/details/118091306
Recommended