您的位置:首页 > 职场人生

面试题三(字符串中提取数字)

2011-09-06 14:07 246 查看
字符串提取数字

完成函数

void take_num(const char *strIn, int *n, unsigned int *outArray)

如输入

strIn="ab00cd+123fght456-25 3.005fgh"

输出

n=6

outArray={ 0, 123, 456, 25, 3, 5 }

不考虑小数如3.005输出3和5

题目分析:将字符串转换成uint,按公式temp=0;temp=temp*10;temp+=str[i]-'0';一直循环。

对于一个数,如果前面是0的话,那么按上面公式也会把0去掉的,也就是会从第一个非零的数开始计数。比如005,temp=0;temp=temp*10(temp=0);temp+=str[i]-'0'(temp=0);当i=i+1时,

按上面过程计算,仍然有temp=0,直到第一个非零的数字出现,这也正符合数的形式。

#include <string.h>
#include <stdio.h>
#include <assert.h>
void take_num(const char *strIn, int *n, unsigned int *outArray)
{
assert(strIn!=NULL && n!=NULL && outArray!=NULL);
int nCount=0;
int lent=strlen(strIn);
int temp=0;
bool IsNum=false;
for (int i=0;i<lent;i++)
{
if (strIn[i]>='0'&& strIn[i]<='9')
{
IsNum=true;
temp=temp*10;
temp+=strIn[i]-'0';
}
else
if (IsNum)
{
outArray[nCount]=temp;
nCount++;
IsNum=false;
temp=0;
}
}
if (IsNum)   ///////一定要对最后一个进行判断,否则就会丢失最后一个数的信心
{
outArray[nCount]=temp;
nCount++;
}
*n=nCount;
}
void main()
{
char str[100]="ab00cd+123fght456-25 3.005fgh12";
int n=0;
unsigned int outstr[100]={0};
take_num(str,&n,outstr);
printf("%d\n",n);
for (int i=0;i<n;i++)
{
printf("%u\t",outstr[i]);
}
printf("\n");

}

其中返回的个数n和输出整型数的个数一样。可巧妙利用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: