码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-27 20:32:48      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   io   for   ar   2014   

识别字符串中的整数并转换为数字形式(40分)

问题描述: 
识别输入字符串中所有的整数,统计整数个数并将这些字符串形式的整数转换为数字形式整数。

要求实现函数: 
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}

 

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 void take_num(const char *strIn, int *n, unsigned int *outArray)
 4 {
 5     int i,j,sum;
 6     const char *p = strIn;
 7     i = 0;
 8     while (*p != \0)
 9     {
10         sum = 0;
11         while(*p < 0 || *p > 9)
12         {   if (*p == \0)
13                 break;
14             p++;
15         }
16         while (*p >= 0 && *p <= 9 )
17         {
18             if (*p == \0)
19                 break;
20             j = *p - 0;
21             sum = sum * 10 + j;
22             p++;
23         }
24         outArray[i] = sum;
25         i++;
26         if (*p == \0)
27             break;
28         p++;
29     }
30     if(*(p-1) >= 0 && *(p-1) <= 9)
31         *n = i;
32     else
33         *n = i-1;
34 }
35 int main()
36 {
37     char str[100];
38     int *n;
39     unsigned int out[100];
40     n = (int*)malloc(sizeof(int));
41     //scanf("%s",str);
42     gets(str);
43     take_num(str,n,out);
44     printf("%d\n",*n);
45     for (int i=0; i < *n; i++)
46         printf("%d ",out[i]);
47     printf("\n");
48     return 0;
49 }

 

 

bubuko.com,布布扣

 

注意判断字符串结尾结束标志。

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

标签:style   blog   http   color   使用   io   for   ar   2014   

原文地址:http://www.cnblogs.com/george-cw/p/3940214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!