首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言字串分割:逗號分隔輸出的兩種實現與常見錯誤

     編輯:程式設計綜合問答

題目需求

輸入格式如 A1,234 的字串(長度 ≤ 20),以逗號分割為兩部分,分行輸出:

輸入:A1,234
輸出1:A1
輸出2:234

原代碼三大錯誤

  1. while(c[i]!=','); 後多一個分號 → 空迴圈體,導致死循環或跳過處理。
  2. printf('\n'); 使用單引號 → 字符常數提升為 int,%c 格式輸出亂碼,應用雙引號 "\n"。
  3. 未處理逗號後可能的空格(題目示例有空格)。

方法一:就地替換逗號為換行符(最簡潔)

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

int main() {
    char str[100];
    fgets(str, sizeof(str), stdin);  // 讀取整行,含換行符

    // 移除 fgets 讀入的尾隨換行符
    str[strcspn(str, "\n")] = '\0';

    for (int i = 0; str[i]; i++) {
        if (str[i] == ',') {
            putchar('\n');  // 直接輸出換行
        } else if (str[i] != ' ') {  // 可選:跳過空格
            putchar(str[i]);
        }
    }
    putchar('\n');
    return 0;
}

方法二:真正分割為兩個子串(標準庫 strtok)

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

int main() {
    char str[100], *token, *parts[2] = {NULL, NULL};
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    int idx = 0;
    token = strtok(str, ",");
    while (token != NULL && idx < 2) {
        // 去除可能的空格
        while (*token == ' ') token++;
        char *end = token + strlen(token) - 1;
        while (end > token && *end == ' ') *end-- = '\0';
        parts[idx++] = token;
        token = strtok(NULL, ",");
    }

    for (int i = 0; i < idx; i++) {
        printf("輸出 %d:%s\n", i + 1, parts[i]);
    }
    return 0;
}

方法三:手動分割(無庫函數,面試常考)

void split_manual(const char *src, char *part1, char *part2) {
    int i = 0, j = 0;
    // 複製第一部分
    while (src[i] && src[i] != ',') {
        if (src[i] != ' ') part1[j++] = src[i];
        i++;
    }
    part1[j] = '\0';
    // 跳過逗號及空格
    while (src[i] && (src[i] == ',' || src[i] == ' ')) i++;
    // 複製第二部分
    j = 0;
    while (src[i]) {
        if (src[i] != ' ') part2[j++] = src[i];
        i++;
    }
    part2[j] = '\0';
}

核心考點總結

  • 輸入處理:fgets + 去尾隨換行,拒絕 gets/scanf("%s")(遇空格截斷)。
  • 邊界條件:無逗號、多逗號、首尾空格、空字串。
  • 輸出格式:嚴格按題目要求「輸出 1:...」帶冒號空格。
  • 指針/索引操作:熟練掌握 strtok、strchr、手動遍歷三種模式。

字串分割是 C 語言基本功,多練手寫版,面試、考試、實戰都游刃有餘。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved