一、问题
有一段文字,其中有若干整数。编写函数,找出其中的整数,存入一个数组中。
函数原型为:
int findint(char *s,int *a);
其中s表示带数字的字符串,a表示存整数的数组,返回值为字符串中的整数个数。字符串中只有正整数。
编写主函数,输入字符串,调用函数识别整数,逆序输出它们。例如,输入字符串“The Wandering Earth exhibition at the China Science and Technology Museum in Beijing, April 4, 2019.”识别数字,输出“2019,4”。
输入:带空格字符串
输出:若干整数,用逗号隔开。
【输入输出样例】
输入:
he Wandering Earth exhibition at the China Science and Technology Museum in Beijing, April 4, 2019.
输出:
2019,4
二、代码
#include <stdio.h>
#include <ctype.h>
// 从字符串中找到整数存到a数组中,返回个数
int findint(char *s, int *a) {
int cnt = 0;
char *p = s;
while (*p != '\0') {
// 如果是数字则开始提取
if (isdigit(*p)) {
int num = 0;
// 循环读取数字
while (isdigit(*p)) {
num = num * 10 + (*p - '0');
p++;
}
a[cnt++] = num;
} else {
p++;
}
}
return cnt;
}
int main() {
char s[1000];
int a[1000], cnt;
// 读取输入字符串
scanf("%[^\n]", s);
// 查找整数
cnt = findint(s, a);
// 逆序输出整数
for (int i = cnt - 1; i >= 0; i--) {
printf("%d", a[i]);
if (i != 0) {
printf(",");
}
}
return 0;
}
三、tips
1.ctype.h
,它提供了一些用于判断字符类型的函数,例如 isdigit()
用于判断一个字符是否是数字字符。这个头文件在代码中用到了。