首页 > 其他 > 详细

识别字符串中的整数并转换为数字形式

时间:2015-04-17 18:12:28      阅读:234      评论:0      收藏:0      [点我收藏+]

接口函数:
void take_num(const char *strIn, int *n, unsigned int *outArray)

【输入】 strIn: 输入的字符串

【输出】 n: 统计识别出来的整数个数

outArray:识别出来的整数值,其中outArray[0]是输入字符串中从左到右第一个整数,outArray[1]是第二个整数,以此类推。数组地址已经分配,可以直接使用

【返回】 无

注:

I、 不考虑字符串中出现的正负号(+, -),即所有转换结果为非负整数(包括0和正整数)

II、 不考虑转换后整数超出范围情况,即测试用例中可能出现的最大整数不会超过unsigned int可处理的范围

III、 需要考虑 ‘0’ 开始的数字字符串情况,比如 “00035” ,应转换为整数35; “000” 应转换为整数0;”00.0035” 应转换为整数0和35(忽略小数点:mmm.nnn当成两个数mmm和nnn来识别)

IV、 输入字符串不会超过100 Bytes,请不用考虑超长字符串的情况。

示例

输入:strIn = “ab00cd+123fght456-25 3.005fgh”

输出:n = 6

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

代码如下:

#include<stdio.h>
#include<stdlib.h>
void take_num(char *strIn, int * n,unsigned  int *outArray)
{
    int i=0;
    int cnt=0;
    while(strIn[i]!=‘\0‘)
    {
        if(strIn[i]>=‘0‘&&strIn[i]<=‘9‘)
        {
            unsigned  int p=1;
            unsigned int t=0;
            int start=i;
            while(strIn[i]>=‘0‘&&strIn[i]<=‘9‘) i++;
            int end=i-1;
            for(int j=end;j>=start;j--)
            {
                t=t+p*(strIn[j]-‘0‘);
                p=p*10;
            }
            cnt++;
            outArray[cnt-1]=t;
        }
        else i++;
    }
    *n=cnt;
}
int main()
{
    char strIn[1000];
    unsigned int outArray[1000];
    int n=0;
    gets(strIn);
    take_num(strIn,&n,outArray); 
    printf("%d\n",n);
    for(int i=0;i<n;i++)
        printf("%d ",outArray[i]);
}

总结几个小问题:
1.void take_num(char strIn, int n,unsigned int *outArray)
中的参数n必须用指针类型,否则调用函数后,n数值不变。
且调用形式为:take_num(strIn,&n,outArray);

2.不要忘了把字符类型的数字转换成整型类型的。

识别字符串中的整数并转换为数字形式

原文:http://blog.csdn.net/sq_what/article/details/45099327

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!