删除C字符串中所有出现的字符 - 需要示例

Ete*_*ner 7 c string

InputString : "I am unwell" "We need to go to the doctor" "How long will it take?".

OutputString: I am unwell We need to go to the doctor How long will it take?

该字符串需要清除所有出现的char ".我可以想到以下的认可

  1. 使用,strchr()函数查找第一次出现 "
  2. 将字符串中的所有字符移动一次位置.

重复步骤1和2,直到strchr()返回NULL指针.

我觉得这是解决这个问题的非常低效的方法.我需要知道,如果还有其他方法可以实现这一目标吗?伪代码或实际代码都将受到赞赏.

R..*_*R.. 18

for (s=d=str;*d=*s;d+=(*s++!='"'));
Run Code Online (Sandbox Code Playgroud)

  • 还有一个:`*s ++ - '"'&& d ++` (2认同)

Lef*_*ium 9

您可以通过访问字符串的每个字符一次来完成此操作.您基本上将字符串复制到自身上,跳过"字符:

伪代码:

  1. 从两个指针开始:SOURCE和DESTINATION.它们都指向字符串的第一个字符.
  2. 如果*SOURCE == NULL设置*DESTINATION = NULL.停止.
  3. 如果*SOURCE!="set*DESTINATION =*SOURCE并增加DESTINATION.
  4. 增加来源.转到第2步.

码:

// assume input is a char* with "I am unwell\" \"We need to go..."

char *src, *dest;

src = dest = input;    // both pointers point to the first char of input
while(*src != '\0')    // exit loop when null terminator reached
{
    if (*src != '\"')  // if source is not a " char
    {
        *dest = *src;  // copy the char at source to destination
        dest++;        // increment destination pointer
    }
    src++;             // increment source pointer
}
*dest = '\0';          // terminate string with null terminator              

// input now contains "I am unwell We need to go..."
Run Code Online (Sandbox Code Playgroud)

更新:修复代码中的一些错误