題目要求
- 從鍵盤輸入字符串,提取所有整數:連續數字構成整數,超過 6 位自動分割(第 7 位起新整數)。
- 對提取的整數升序排序。
- 輸出所有整數。
- 編寫測試主程序,不使用指針。
核心邏輯解析
- 提取規則:遍歷字符串,遇到數字累積
temp = temp * 10 + (ch - '0');若 temp > 99999(超 6 位),將 temp / 10 存入數組,temp = 寬位數字 繼續累積。
- 排序算法:採用計數排序(桶排序),利用輔助數組
ad_num[100000] 記錄每個數值出現次數,再按順序回填,時間復雜度 O(N+K),適合 0-99999 範圍整數。
完整代碼(註釋詳盡)
#include <stdio.h>
#include <stdlib.h>
char string[1000]; // 輸入字符串緩衝區
int num[100]; // 提取出的整數數組
int ad_num[100000]; // 計數排序輔助數組(桶)
// 函數聲明
int Convert(char *s); // 提取整數,返回個數
void Sort(int c); // 計數排序
void Print(int c); // 輸出數組
int main() {
int num_Count;
printf("請輸入您的字符串文本(回車結束):\n");
scanf("%s", string); // 注意:%s 遇空白停止,含空格請用 fgets
num_Count = Convert(string);
printf("提取的整數:\n");
for (int i = 0; i < num_Count; i++) printf("%d ", num[i]);
printf("\n排序後:\n");
Sort(num_Count);
Print(num_Count);
printf("\n程序結束。\n");
system("pause");
return 0;
}
// 提取整數核心邏輯
int Convert(char *s) {
int count = 0, temp = 0, a = 0;
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] >= '0' && s[i] <= '9') {
temp = temp * 10 + (s[i] - '0');
if (temp > 99999) { // 超過 6 位
num[a] = (temp - (s[i] - '0')) / 10; // 存入前 6 位
temp = s[i] - '0'; // 第 7 位作為新數起始
a++; count++;
}
} else {
if (temp > 0) { // 非數字結束,存入當前數
num[a++] = temp;
temp = 0;
count++;
}
}
}
if (temp > 0) { num[a++] = temp; count++; } // 字符串結尾處理
return count;
}
// 計數排序(桶排序)
void Sort(int c) {
int a = 0;
for (int i = 0; i < c; i++) ad_num[num[i]]++; // 統計頻次
for (int i = 0; i < 100000; i++) {
while (ad_num[i] > 0) {
num[a++] = i; // 回填排序後數組
ad_num[i]--;
}
}
}
void Print(int c) {
for (int i = 0; i < c; i++) printf("%d ", num[i]);
}
關鍵點總結
- 不使用指針,僅用數組下標模擬動態存儲。
- 計數排序適用於已知範圍(0-99999)整數,極快且穩定。
- 輸入用
scanf("%s") 僅讀單詞,含空格請改用 fgets(string, sizeof(string), stdin) 並去除換行符。
- 數組大小 100/100000 足夠應對題目規模,實際工程中應動態分配或用鏈表。