c - 在 C 中将所有数字从字符串导入到数组

标签 c arrays string

需要查找字符串中的所有数字。 (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/

相关文章:

ruby-on-rails - Rails ActiveRecord update_all id 数组

c# - 用于验证逻辑 && || 的正则表达式字符串中的运算符

c - 线程 : when Dynamic mutex initialization must be used

c++ - 在C程序中集成Prolog

java - 无法理解如何创建链表数组

Javascript 循环对象数组并返回第一个值

计算给定字符串的 float 的长度

java - 使用反射设置字段 - String 没有 valueOf(String) 方法

c - C 中带有指针的 int 矩阵 - 内存分配困惑

c - 反转链表而不修改头指针