C语言如何从字符串中提取数字?

99ANYc3cd6
预计阅读时长 16 分钟
位置: 首页 C语言 正文

从字符串中提取数字的C语言实现

在C语言中,从字符串中提取数字有几种常见的方法,下面我将介绍几种不同的实现方式。

从字符串中提取数字 c语言
(图片来源网络,侵删)

方法1:使用标准库函数

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int extract_numbers(const char *str) {
    int num = 0;
    int found = 0;
    while (*str) {
        if (isdigit(*str)) {
            num = num * 10 + (*str - '0');
            found = 1;
        } else if (found) {
            printf("提取的数字: %d\n", num);
            num = 0;
            found = 0;
        }
        str++;
    }
    // 处理字符串末尾的数字
    if (found) {
        printf("提取的数字: %d\n", num);
    }
    return 0;
}
int main() {
    char str[] = "abc123def45gh6";
    extract_numbers(str);
    return 0;
}

方法2:提取所有连续数字并存储到数组

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_NUMBERS 100
int extract_numbers_to_array(const char *str, int numbers[], int *count) {
    *count = 0;
    int current_num = 0;
    int found = 0;
    while (*str) {
        if (isdigit(*str)) {
            current_num = current_num * 10 + (*str - '0');
            found = 1;
        } else if (found) {
            if (*count < MAX_NUMBERS) {
                numbers[*count] = current_num;
                (*count)++;
            }
            current_num = 0;
            found = 0;
        }
        str++;
    }
    // 处理字符串末尾的数字
    if (found && *count < MAX_NUMBERS) {
        numbers[*count] = current_num;
        (*count)++;
    }
    return 0;
}
int main() {
    char str[] = "abc123def45gh6";
    int numbers[MAX_NUMBERS];
    int count = 0;
    extract_numbers_to_array(str, numbers, &count);
    printf("提取的数字有:\n");
    for (int i = 0; i < count; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");
    return 0;
}

方法3:使用正则表达式(POSIX标准)

#include <stdio.h>
#include <regex.h>
#include <stdlib.h>
int extract_with_regex(const char *str) {
    regex_t regex;
    int reti;
    char msgbuf[100];
    // 编译正则表达式匹配一个或多个数字
    reti = regcomp(&regex, "[0-9]+", REG_EXTENDED);
    if (reti) {
        fprintf(stderr, "无法编译正则表达式\n");
        return 1;
    }
    // 执行匹配
    regmatch_t pmatch[1];
    const char *search_start = str;
    while (regexec(&regex, search_start, 1, pmatch, 0) == 0) {
        // 计算数字的起始和结束位置
        int start = pmatch[0].rm_so;
        int end = pmatch[0].rm_eo;
        // 提取数字字符串
        char num_str[end - start + 1];
        strncpy(num_str, search_start + start, end - start);
        num_str[end - start] = '\0';
        // 转换为整数并打印
        int num = atoi(num_str);
        printf("提取的数字: %d\n", num);
        // 移动搜索位置
        search_start += end;
    }
    // 释放正则表达式
    regfree(&regex);
    return 0;
}
int main() {
    char str[] = "abc123def45gh6";
    extract_with_regex(str);
    return 0;
}

方法4:处理浮点数

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
double extract_double(const char *str) {
    char *endptr;
    double num = strtod(str, &endptr);
    if (endptr == str) {
        printf("没有找到数字\n");
        return 0.0;
    }
    return num;
}
int extract_all_doubles(const char *str) {
    const char *ptr = str;
    char num_str[100];
    int i;
    while (*ptr) {
        if (isdigit(*ptr) || *ptr == '.') {
            i = 0;
            // 收集数字字符
            while (isdigit(*ptr) || *ptr == '.') {
                num_str[i++] = *ptr++;
            }
            num_str[i] = '\0';
            // 转换为double
            double num = atof(num_str);
            printf("提取的浮点数: %f\n", num);
        } else {
            ptr++;
        }
    }
    return 0;
}
int main() {
    char str[] = "abc123.45def6.78gh9";
    extract_all_doubles(str);
    return 0;
}

注意事项

  1. 这些方法假设数字是连续的十进制数字
  2. 对于浮点数,需要额外处理小数点
  3. 方法3需要POSIX支持,不是所有C环境都支持
  4. 方法2需要预先知道可能的最大数字数量
  5. 实际应用中可能需要考虑负数、科学计数法等情况

选择哪种方法取决于你的具体需求和运行环境,对于简单的整数提取,方法1或方法2可能更合适;对于复杂的数字格式,方法3或方法4可能更好。

从字符串中提取数字 c语言
(图片来源网络,侵删)
-- 展开阅读全文 --
头像
织梦会员中心如何调用文章?
« 上一篇 03-07
织梦栏目动态链接地址如何获取?
下一篇 » 03-07

相关文章

取消
微信二维码
支付宝二维码

目录[+]