# **檔案路徑分隔符問題** 程式題目: 在程式設計領域中,我們往往希望程式具有「可攜性(portability)」,也就是我們可以一支程式只寫一次,就可以通用在各種不同的作業系統中,如常見的 Linux、MacOS 和 Windows。然而想要做到這點卻沒有那麽容易,問題往往比想象中的多。而「**檔案路徑分隔符**」就是其中一個惱人的問題。 在 Windows 系統下,使用了反斜線(\)作為分隔檔案路徑的符號,如:“projects\oj\xyz”;然而 Linux 及 MacOS 所使用的是正斜線(/),如:“project/oj/xyz”。 在本題中,給定一種系統下的路徑,請你寫程式將其轉換成另一種系統的路徑(也就是反斜線變成正斜線;正斜線變成反斜線)。 輸入規則: 輸入僅有一行,包含一個路徑,該路徑有以下限制: * 長度介於 1 至 200 之間 * 路徑元素數量不會超過 100 個 * 只可能包含大小寫字母、底線、點(.)、數字、空白,以及正或反斜線 * 一條路徑中的斜線只可能「全為正斜線」或「全為反斜線」,不會有混用的情況 * 開頭或結尾保證不會是斜線符號,並保證不會有空的路徑元素(例如:xyz/abc//uuu) 輸出規則: 輸出一共有若干行: * 前 N 行為該輸入路徑的所有單位元素(如範例所示) * 第 N+1行為以下操作的輸出: * 如果是 Windows 的路徑(使用反斜線 \),將其轉換成 Linux 的路徑(使用正斜線 /) * 如果是 Linux 的,則轉換成 Windows 的路徑 輸入範例: ``` rekk\ntu\ntu_misc\istp\rekkoj\0010_file_path ``` 輸出範例: ``` rekk ntu ntu_misc istp rekkoj 0010_file_path rekk/ntu/ntu_misc/istp/rekkoj/0010_file_path ``` 以下為我的程式碼: ```c #include <stdio.h> #include <string.h> int main() { char inputPath[201]; int slashCount = 0; fgets(inputPath, sizeof(inputPath), stdin); int len = strlen(inputPath); if (inputPath[len - 1] == '\n') { inputPath[len - 1] = '\0'; len--; } int i; for (i = 0; inputPath[i] != '\0'; i++) { if (inputPath[i] == '/') { slashCount++; } } int backslashCount = 0; int j; for (j = 0; inputPath[j] != '\0'; j++) { if (inputPath[j] == '\\') { backslashCount++; } } if (backslashCount > 0 && slashCount > 0) return 0; if (slashCount - 1 > 100) return 0; if (inputPath[0] == '/' || inputPath[0] == '\\') return 0; if (inputPath[i - 1] == '/' || inputPath[j - 1] == '\\') return 0; for (int i = 0; inputPath[i + 1] != '\0'; i++) { if (inputPath[i] == '/' && inputPath[i + 1] == '/') return 0; } for (int j = 0; inputPath[j + 1] != '\0'; j++) { if (inputPath[j] == '\\' && inputPath[j + 1] == '\\') return 0; } char originalSep = (slashCount > 0) ? '/' : '\\'; i = 0; while (inputPath[i] != '\0') { char segment[201] = ""; j = 0; while (inputPath[i] != '\0' && inputPath[i] != originalSep) { segment[j++] = inputPath[i++]; } segment[j] = '\0'; printf("%s\n", segment); if (inputPath[i] == originalSep) i++; } char convertedSep = (slashCount > 0) ? '\\' : '/'; i = 0; while (inputPath[i] != '\0') { char segment2[201] = ""; j = 0; while (inputPath[i] != '\0' && inputPath[i] != originalSep) { segment2[j++] = inputPath[i++]; } segment2[j] = '\0'; if (inputPath[i] != '\0') { printf("%s%c", segment2, convertedSep); } else { printf("%s", segment2); } if (inputPath[i] == originalSep) i++; } return 0; } ```