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


    识别字符串中的整数并转换为数字形式(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 != '')
     9     {
    10         sum = 0;
    11         while(*p < '0' || *p > '9')
    12         {   if (*p == '')
    13                 break;
    14             p++;
    15         }
    16         while (*p >= '0' && *p <= '9' )
    17         {
    18             if (*p == '')
    19                 break;
    20             j = *p - '0';
    21             sum = sum * 10 + j;
    22             p++;
    23         }
    24         outArray[i] = sum;
    25         i++;
    26         if (*p == '')
    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);
    45     for (int i=0; i < *n; i++)
    46         printf("%d ",out[i]);
    47     printf("
    ");
    48     return 0;
    49 }

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

  • 相关阅读:
    TypeError: Iterator operand 0 dtype could not be cast from dtype('<M8[us]') to dtype('<M8[D]') according to the rule 'safe'
    Linux中matplotlib 中文显示问题解决
    自己动手实现爬虫scrapy框架思路汇总
    机器学习算法之多项式回归
    scrapy爬虫--苏宁图书
    Mongodb数据库基本操作
    day04 Python
    day03 Python爬虫
    day02 Python完结
    day01 python基础
  • 原文地址:https://www.cnblogs.com/george-cw/p/3940214.html
Copyright © 2020-2023  润新知