首页 > 编程语言 > 详细

【学习笔记】C语言习题:统计字符串中整数数量并列出

时间:2020-05-02 09:14:21      阅读:63      评论:0      收藏:0      [点我收藏+]
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 256 //字符串最大长度+1
#define is_number(ch) ((‘0‘<=(ch)) && ((ch)<=‘9‘)) //判断字符是否为数字

int main(){
    char * str=(char *)malloc(SIZE); //声明字符串并给它分配内存
    int a[SIZE]={0},count=0; //数组a存储整数,count统计整数数量
    fgets(str,SIZE,stdin);
    for(int i=0;i<strlen(str);i++){
        if(is_number(*(str+i))){
            a[count]=10*a[count]+*(str+i)-48; //在ASCII码中,一个数字减去48是它本身的码值
            if(!is_number(*(str+i+1)))
                count++; //下一个字符不是数字,则单个整数完成统计
        }
    }
    printf("一共有%d个整数\n",count); 
    for(int i=0;i<count;i++) printf("第%d个是%d\n",i+1,a[i]);

    system("pause");
    return 0;
}

输入:114iiyo514koiyo1919tdkr810ton

输出:

一共有4个整数
第1个是114
第2个是514
第3个是1919
第4个是810

题目来源:《C程序设计 第五版》谭浩强 第八章16题

【学习笔记】C语言习题:统计字符串中整数数量并列出

原文:https://www.cnblogs.com/adesoe/p/12815657.html

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