程序包含四個任務:
1. 比較兩字符串大小並輸出關系(>, =, <)。
2. 將 str2 插入 str1 指定位置 n,並將下標 x 到 y 之間字符轉大寫,輸出結果長度。
3. 將處理後的字符串轉小寫存入 str2,再比較 str3 與 str2 大小。
4. 根據長度條件輸出 str3 或 str2。
str3、str2 直接賦值未清零,導致 strlen 計算錯誤。strlen 動態控制,避免越界或多餘處理。for(i=len_str1,j=0;i<n+len_str1;i++,j++) 中 n 為插入長度?題意應為插入前 n 個字符,需重新審視。for(i=x;i<=y;i++) 可能越界,需加邊界檢查。// 任務2:安全插入並轉大寫
memset(str3, 0, sizeof(str3)); // 關鍵:先清零
strcpy(str3, str1); // 複製 str1 到 str3
if (n >= len_str2) { // n 超過 str2 長度,整體拼接
strcat(str3, str2);
} else { // 只取 str2 前 n 字符拼接
strncat(str3, str2, n);
}
// 區間轉大寫(下標從 0 開始,含邊界)
int start = max(0, x);
int end = min((int)strlen(str3)-1, y);
for (int i = start; i <= end; i++) {
str3[i] = toupper((unsigned char)str3[i]);
}
printf("the length of \"%s\" is %d\n", str3, (int)strlen(str3));
memset 或 {0} 初始化所有字符數組。strncpy、strncat 等帶長度限制的安全函數。
