需求:從字符串提取數字字符拼接,去除前導零。例:00000hfjkahk353k5hkhdf900kdk45 → 353590045。
bool started = false; // 是否已遇到第一個非零數字
for (int i = 0; s[i]; i++) {
if (s[i] >= '0' && s[i] <= '9') {
if (started || s[i] != '0') { // 已開始 或 當前非零
if (s[i] != '0') started = true; // 遇到第一個非零
result[idx++] = s[i];
}
}
}
result[idx] = '\0';
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main() {
char s[1000], res[1000];
int caseNo = 0;
while (scanf("%s", s) != EOF) {
caseNo++;
int idx = 0;
bool started = false;
for (int i = 0; s[i]; i++) {
if (s[i] >= '0' && s[i] <= '9') {
if (started || s[i] != '0') {
if (s[i] != '0') started = true;
res[idx++] = s[i];
}
}
}
res[idx] = '\0';
printf("Case #%d:\n%s\n", caseNo, res);
}
return 0;
}
started 確保第一個非零數字前的所有零被跳過,之後的零(如 900 中的零)正常保留。res 為空串,輸出空行符合題意。