You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

提取字符串中的数字:输入格式转换及C代码实现问询

调试提取字符串中数字的C代码

首先明确需求:当输入格式为{1,32,33,41,59}时,需要提取其中的数字并输出为空格分隔的序列1 32 33 41 59。

你提供的代码还未完成,先把现有代码贴出来:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
    char input[200],words[10][10];
    int length=0,i=0,j=0,k=0,t;
    fgets(input,200,stdin);
    //counting the length of str
    while(input[length] != '\0') {
        length++;
    }
    for(i=1;i<=length;i++) {
        if(input[i] == ',' || input[i] == '}') {
            words[j][k] = '\0';
            j++...

我来帮你完善和调试这个代码,先说说现有代码里的几个小问题:

  • 循环条件i<=length不合理,字符串索引从0开始,input[length]是字符串结束符\0,应该改成i < length
  • 遇到,或}时,只执行了j++但没重置k的值,会导致下一个数字覆盖上一个数字的后续位置,引发内容错误或数组越界
  • 缺少后续输出逻辑:收集完数字后,没有循环输出这些数字的步骤

基于你原始思路的完善版本

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {
    char input[200], words[10][10];
    int length = 0, i = 0, j = 0, k = 0;
    
    // 读取输入内容
    fgets(input, 200, stdin);
    // 去掉fgets可能读取到的换行符,避免干扰后续处理
    input[strcspn(input, "\n")] = '\0';
    
    // 直接用strlen计算字符串长度,比手动遍历更简洁
    length = strlen(input);
    
    // 从索引1开始,跳过开头的'{'
    for(i = 1; i < length; i++) {
        if(input[i] == ',' || input[i] == '}') {
            // 给当前数字字符串添加结束符
            words[j][k] = '\0';
            j++;
            k = 0; // 重置k,准备存储下一个数字
            // 遇到'}'就提前退出循环,无需继续遍历
            if(input[i] == '}') {
                break;
            }
        } else {
            // 收集当前数字的每一个字符
            words[j][k] = input[i];
            k++;
        }
    }
    
    // 输出所有数字,用空格分隔
    for(int t = 0; t < j; t++) {
        printf("%s ", words[t]);
    }
    // 最后换行,让输出格式更规范
    printf("\n");
    
    return 0;
}

更简洁的实现方式(用strtok分割)

如果不想手动处理字符遍历,C标准库的strtok函数可以直接帮我们分割字符串,代码会更简洁高效:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {
    char input[200];
    // 读取输入内容
    fgets(input, 200, stdin);
    // 去掉换行符
    input[strcspn(input, "\n")] = '\0';
    
    // 用'{'、','、'}'作为分隔符,分割出所有数字字符串
    char *token = strtok(input, "{,}");
    while (token != NULL) {
        // 输出每个数字,后面加空格
        printf("%s ", token);
        // 继续分割下一个数字
        token = strtok(NULL, "{,}");
    }
    printf("\n");
    
    return 0;
}

这两个版本都能实现你的需求,测试输入{1,32,33,41,59}时,都会输出1 32 33 41 59 (如果想去掉最后一个多余的空格,可以稍微调整输出逻辑:比如记录第一个数字,后续数字先输出空格再输出数字)。

内容的提问来源于stack exchange,提问作者Syed Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:49:14