面试题三(字符串中提取数字)
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,直到第一个非零的数字出现,这也正符合数的形式。
其中返回的个数n和输出整型数的个数一样。可巧妙利用
完成函数
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和输出整型数的个数一样。可巧妙利用
相关文章推荐
- [原]Java面试题-将字符串中数字提取出来排序后输出
- SQL函数:字符串中提取数字,英文,中文,过滤重复字符
- C# 提取字符串中的数字
- 字符串提取数字
- 关于Java从字符串中提取数字的方法
- 一道面试题 不用long的相关api将数字字符串转换成long
- 字符串提取数字/汉字/英文字母
- 提取字符串里面的数字
- js实现在字符串中提取数字 和字母
- 面试题:字符串转化为数字
- android String字符串中提取数字
- 将数字从《字符串》中提取出来
- 黑马程序员---如何处理将字符串里的数字提取出来和将字符串里的空格去掉?
- oracle利用正则表达式提取字符串中的数字
- 提取字符串中数字、中文、英文字符…
- 从文件读字符串,提取其中的数字,然后进行集合划分
- java正则表达式提取字符串中的数字
- 字符串中提取数字的实现(c++)
- JAVA学习60_Java从字符串中提取数字
- php提取字符串中的数字