C语言小练习:输入一个字符串,内有数字和非数int字符,如a123x456,将其中连续的数作为一个整数,依次存放到整形数组a中。

例:123存放在a[0],456存放在a[1]。统计共有多少整数,并输出这些整数

#include<stdio.h>
int main(int argc, char const *argv[])
{
    char buf[32]="a123b456";
    int a[32]={};
    int i=0,j=0,sum=0;
    char *p = buf;
    while(*p)
    {
        if(*p < '0'|| *p > '9')
        {
            p++;
            continue;
        }
        while(*p >= '0'&&*p <= '9')
        {
            sum = sum*10 + *p -48;
            p++;
        }
        a[i] = sum;
        sum = 0;
        i++;//存放整数的个数
    }
    printf("一共有%d个整数,他们分别是:\n",i);
    while(j<i)
    {
        printf("%d ",a[j]);
        j++;
    }
    printf("\n");
    return 0;
}

要解决这个问题,你可以按照以下步骤编写C语言程序: 1. 首先,我们需要定义一个来分割输入字符串并提取连续数字: ```c #include <stdio.h> #include <ctype.h> // 函用于找出字符串中的连续数字序列 int* extractNumbers(char str[], int* count) { char num[20]; // 存储当前数字 int numIndex = 0; int arrIndex = 0; while (str[arrIndex]) { if (isdigit(str[arrIndex])) { // 如果字符数字 num[numIndex++] = str[arrIndex]; if (numIndex == 20) { // 数字超过最大长度,清零并开始新一次存储 numIndex = 0; if (*count != 0) ++(*count); // 数组已满,增加计 else *count = 1; // 首个数字 } } else { // 遇到数字字符,结束当前数字的收集 num[numIndex] = '\0'; // 添加终止符 *(arrIndex + *count++) = atoi(num); // 转换数字并存入结果数组 numIndex = 0; } ++arrIndex; } // 处理最后一个可能的数字 if (numIndex > 0) { num[numIndex] = '\0'; *(arrIndex + *count) = atoi(num); } return &(*(arrIndex+*count)); // 返回指向结果数组的指针 } // 比较两个整数数组的函 int compareArrays(int a[], int b[], int n) { for (int i = 0; i < n; i++) { if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; } return 0; // 如果数组相等 } int main() { char str[] = "A123x456 17960?302tab5876"; int numCount = 0; int* numbers = extractNumbers(str, &numCount); printf("There are %d integers in the string:\n", numCount); for (int i = 0; i < numCount; i++) printf("%d ", numbers[i]); // 示例对比两个数组 int arr1[] = {1, 2, 3}; int arr2[] = {4, 5, 6}; int result = compareArrays(arr1, arr2, 3); if (result < 0) printf("\nArray 1 is smaller than Array 2.\n"); else if (result > 0) printf("\nArray 1 is larger than Array 2.\n"); return 0; } ``` 在这个程序中,我们首先定义了一个`extractNumbers`用于提取连续数字,然后定义了`compareArrays`函来比较两个整数数组。在`main`函中,我们测试了这两个功能并展示了如何使用它们。注意,这里假设数组大小足够大,实际应用中可能需要动态分配空间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值