C 如何编辑和使用包含双引号和转义字符的字符串?
如何编辑带有双引号和反斜杠的字符串 “我喜欢“编程” 然后像这样打印 我喜欢“编程” 我在网上找到了这个,但运气不好:C 如何编辑和使用包含双引号和转义字符的字符串?,c,string,edit,C,String,Edit,如何编辑带有双引号和反斜杠的字符串 “我喜欢“编程” 然后像这样打印 我喜欢“编程” 我在网上找到了这个,但运气不好: for (int i = 0; i < lineLength; i++) { if (line[i] == '\\') { line[j++] = line[i++]; line[j++] = line[i]; if (line[i] == '\0') break; }
for (int i = 0; i < lineLength; i++)
{
if (line[i] == '\\')
{
line[j++] = line[i++];
line[j++] = line[i];
if (line[i] == '\0')
break;
}
else if (line[i] != '"')
line[j++] = line[i];
}
line[j] = '\0';
for(int i=0;i
当您遇到反斜杠时,您当前正在复制反斜杠和下一个字符。您实际需要做的只是增加反斜杠,然后复制下一个字符,就像它不是反斜杠或引号时一样。而不是行[j++]=行[i++];
(对于if
正文中的第一行)您只需要i++;
您还可以解决一些其他问题,但这应该可以让它正常工作。在处理这些删除字符的问题时,读/写指针方法是最简单的方法之一,它使算法易于遵循
void RemoveQuotes(char * Str)
{
const char * readPtr=Str;
char * writePtr=Str;
for( ;*readPtr; readPtr++, writePtr++)
{
/* Checks the current character */
switch(*readPtr)
{
case '\"':
/* if there's another character after this, skip the " */
if(readPtr[1])
readPtr++;
/* otherwise jump to the check and thus exit from the loop */
else
continue;
break;
case '\\':
/* if a " follows, move readPtr ahead, so to skip the \ and copy
the "; otherwise nothing special happens */
if(readPtr[1]=='\"')
readPtr++;
break;
}
/* copy the characters */
*writePtr=*readPtr;
}
/* remember to NUL-terminate the string */
*writePtr=0;
}
我刚刚在堆栈溢出中搜索了“删除C中的引号”“-这是#1回答:@michael15您能将问题中的代码更改为完整的C函数,并包含一些示例输入和预期输出吗?我们需要知道你遇到了什么问题。你为什么要对此做些什么?它将按您想要的方式打印。@michael15在您的问题末尾会有一个链接,上面写着“编辑”。你可以用它来改变你的问题。(详情请参阅。)“答案”部分是发布解决方案的地方。