You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言特殊字符替换问题:单引号转义结果不符求排查

你的代码问题出在处理单引号时的索引更新错误

你遇到的问题是因为在替换单引号为\'的时候,没有正确更新目标数组的索引j,导致后续字符直接覆盖了刚写入的单引号。

错误原因分析

当代码检测到单引号时,你执行了这几步:

pch[j] = '\\';
pch[++j] = str[i];
continue;

这里的++j确实让j增加了1,把单引号写入了pch[j],但此时j的值只比初始值大1——而你实际上写入了两个字符(反斜杠和单引号),j需要再增加1才能让下一个字符写到正确的位置。结果就是,下一次循环时,新的字符直接覆盖了刚写入的单引号,最终输出就少了单引号,变成了HELLO\All。

修正后的代码

只需要调整索引更新逻辑,确保写入两个字符后j增加2:

#include <stdio.h>
#include <string.h>
int main() {
    int i, j = 0;
    char str[] = "HELLO'All";
    char pch[128] = { 0 };
    for (i = 0; i < strlen(str); i++) {
        if (str[i] == '\'') {
            pch[j] = '\\';
            printf(" pch[%d] = *%c* \n", j, pch[j]);
            j++; // 移动到下一个位置存储单引号
            pch[j] = str[i];
            printf(" pch[%d] = *%c* \n", j, pch[j]);
            j++; // 再次移动索引,为后续字符留出位置
            continue;
        }
        pch[j++] = str[i];
    }
    printf("pch = *%s* \n", pch);
    return 0;
}

验证结果

运行修正后的代码,你会得到预期的输出:pch = *HELLO\'All*。

内容的提问来源于stack exchange,提问作者Anis_Stack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:38:59