gpt4 book ai didi

C 替换特殊字符

转载 作者:行者123 更新时间:2023-11-30 20:50:11 26 4
gpt4 key购买 nike

我想将 ' 字符替换为 \' 我使用以下代码:

#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]);
pch[++j] = str[i];
continue;
}
pch[j++] = str[i];
}
printf("pch = *%s* \n", pch);
return 0;
}

我得到结果:pch = *HELLO\All*
预期结果:pch = *HELLO\'All*
我的代码中缺少什么?

最佳答案

您似乎错过了 j 的增量

尝试这样

  pch[j++]='\\';
printf(" pch[%d] = *%c* \n",j-1, pch[j-1]);
pch[j++]=str[i];

或者像这样

  pch[j]='\\';
printf(" pch[%d] = *%c* \n",j, pch[j]);
++j;
pch[j++]=str[i];

关于C 替换特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com