需要查找字符串中的所有数字。 (54g 不是数字等)并导入到数组。如何将数字导入数组?如何摆脱 87) 等?
#include "stdio.h"
int main() {
char *pS;
int i;
char str[100];
short isn = 0;
gets(str);
pS = str;
int a[100]={0};
i=0;
while (*pS) {
if (*pS >= '0' && *pS <= '9') {
isn = 1;
printf("%c", *pS);
}
else {
if (isn) {
isn = 0;
printf(" ");
}
}
pS++;
}
return 0;
}
最佳答案
我不太清楚您的要求,但根据您发布的代码,您似乎希望将所有相邻数字视为单个值并忽略之间的任何非数字。如果是这种情况,我会首先将所有非数字转换为通用字符值(选择任何非数字字符),然后使用 strtok
来标记字符串:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
char str[100];
char* s;
int a[100];
int count;
int len;
int i;
fgets(str, sizeof(str), stdin);
/* change all non-digits to spaces */
len = strlen(str);
for (i = 0; i < len; ++i) {
if (!isdigit(str[i]))
str[i] = ' ';
}
count = 0;
/* tokenize on spaces and append to array */
s = strtok(str, " ");
while (s != NULL) {
a[count++] = atoi(s);
s = strtok(NULL, " ");
}
/* output final array */
for (i = 0; i < count; ++i)
printf("%d\n", a[i]);
return 0;
}
关于c - 在 C 中将所有数字从字符串导入到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33983983/