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

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?

字符串需要清除所有出现的字符" 。我可以想到以下的批准

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

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

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

 for (s=d=str;*d=*s;d+=(*s++!='"')); 

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

伪代码:

  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..." 

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

而不是“就地”移动字符来覆盖要删除的字符,而是创建一个新字符串。

这样可以最大限度地减少复制每个有效字符一次所复制的字符数。 使用原始方法,字符串末尾附近的字符将被复制n次,其中n是其前面的无效字符数。

如果你的字符串不是很大,那么显而易见的答案就是拥有一个单独的字符串。 一个循环,直到你得到\ 0(字符串结束)有一个循环(给你O(n))和一个比较来检查字符串的当前位置是否是有问题的字符(再次O(n))

在所有 :


  s1 = original array s2 = new array to store the final result c = character in question. current_pointer = 0 new_pointer =0 while(s1[current_pointer] != '\0') { ele = s1[current_pointer] ; if( ele != c) { s2[new_pointer++] = ele } current_pointer++ } 

请注意,此方法仅在字符串大小较小时有效。 随着字符串大小的增加,我们需要寻求更好的方法。

希望这可以帮助。