编辑代码

#include <stdio.h>

/**
 * 将连续的 \r\n 替换为一个 '0',单独存在的 \r 或 \n 保留
 * @param str 输入字符串(原地修改)
 */
void replace_crlf_pairs_with_zero(char *str) {
    if (str == NULL) return;
    int j = 0; // 写指针
    for (int i = 0; str[i] != '\0'; ) {
        // 检查是否是连续的 \r\n
        if (str[i] == '\r' && str[i+1] == '\n') {
            str[j++] = '0'; // 替换为 '0'
            i += 2;         // 跳过已处理的 \r\n
        } else {
            str[j++] = str[i++]; // 保留其他字符
        }
    }
    str[j] = '\0'; // 确保字符串终止
}


int main() {
    // 情景1验证
    char test1[] = "Hello\r\nWorld\r";
    replace_crlf_with_zero(test1);
    printf("单独替换结果: %s\n", test1); // 输出: Hello00World0

    // 情景2验证
    char test2[] = "Line1\r\nLine2\rEnd\n";
    replace_crlf_pairs_with_zero(test2);
    printf("替换连续组合结果: %s\n", test2); // 输出: Line10Line2\rEnd\n

    return 0;
}