繁体   English   中英

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

[英]remove all occurences of a character in C string - Example needed

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指针。

我认为这是解决此问题的非常无效的方法。 我需要知道,是否还有其他方法可以实现? 伪代码或实际代码都将受到赞赏。

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

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

伪代码:

  1. 从两个指针开始:SOURCE和DESTINATION。 它们都指向字符串的第一个字符。
  2. 如果* SOURCE == NULL设置* DESTINATION = NULL。 停止。
  3. 如果* SOURCE!=“设置* 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++
  }

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

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM