將字符串中每個空格替換為 "%20"。假設數組空間足夠。關鍵:從後向前掃描,避免覆蓋未處理字符。
counti 指向原末尾,j 指向新末尾i == j 結束#include <stdio.h>
#include <string.h>
int main() {
char arr[100] = "we are happy.";
int len = strlen(arr);
int count = 0;
// 統計空格
for (int i = 0; i < len; i++)
if (arr[i] == ' ') count++;
int i = len - 1;
int j = len - 1 + 2 * count;
arr[j + 1] = '\0'; // 新結束符
while (i >= 0) {
if (arr[i] == ' ') {
arr[j--] = '0';
arr[j--] = '2';
arr[j--] = '%';
} else {
arr[j--] = arr[i];
}
i--;
}
printf("結果:%s\n", arr);
return 0;
}
原串:w e a r e h a p p y . (長13,2空格) 新長:13 + 4 = 17 i=12 j=16 步驟:從後向前複製/替換 結果:we%20are%20happy.
char *replace_spaces(const char *s) {
int len = strlen(s), count = 0;
for (int i=0;i