删除s1中与s2中任何字符匹配的每个字符

时间:2014-07-06 04:34:30

标签: c

任何人都可以看到我的代码有什么问题吗?非常感谢你!

squeeze2将两个char数组作为参数。它删除第一个数组中与第二个数组中任何字符匹配的每个字符。例如:如果第一个是"你好"第二个是" ea",然后第一个数组将成为" hllo"。

对于外循环的每次迭代,a[i]都是一个特定的数字。我们称之为c。每次非c发生时,它都会被复制到当前k位置,然后才会增加k以便为下一个字符做好准备。

void squeeze2(char s[], char a[]){
    int i, j, k;/*Remove elements of a from s*/
    i=j=k=0;
    while(a[i++] != '\0'){
        k = 0;
        while(s[j++]!= '\0'){
            if(s[j]!= a[i]){
                s[k++] = s[j];
            }
        }
    }
    s[k] = '\0';
}

2 个答案:

答案 0 :(得分:1)

这是我解决您问题的方法。 设s1为需要删除字母的字符串,让s2为包含要查找的元素的字符串。

void squeeze2(char s1[], char s2[]){
  int i, j, k;/*Remove elements of a from s*/
  i=j=k=0;

  /* For each character in s2... */
  while(s2[i] != '\0'){ // Note change of i++ to i

      /* Search for the character in s1...*/
      j = k = 0; // Counters for string1
      while(s1[j]!= '\0'){

        /* If we find a match, remove the character... ('shift' the remaining characters 1 index to the left, overwriting the current character)*/
        if(s1[j]== s2[i]){
            k = j //Start at j
            while(s1[k] != '\0'){ //again, I don't start with k++, just k
              s1[k] = s1[k+1]; // The null-terminator gets copied too.
              k++;
            }
        j++;
        }
      }
      i++;
  }
  //The following line is not necessary because the null-terminator is copied
  //s1[k] = '\0';  
  }

请记住标记正确答案。

答案 1 :(得分:1)

您的原始代码即将开始工作,但您只是犯了几个愚蠢的错误。例如。 while(s [j ++] ...但是你在下一行检查s [j],它应该是j的旧值,而不是新值。还需要在循环之前将j重置为0。

我建议将两个循环更改为标准循环。您还可以使用constrestrict来帮助您的编译器:

void squeeze2(char *restrict s, char const *restrict remove)
{
/* Loop through 'remove' taking each char out of `s` */
    for (; *remove; ++remove)
    {
        size_t out = 0;
        for (size_t in = 0; s[in]; ++in)
        {
            if ( s[in] != *remove )
                s[out++] = s[in];
        }
        s[out] = 0;
    }
}

实际上我的偏好是反过来循环:循环s;并使用strchr函数来决定是否保留当前字符。它更容易阅读,写的更少:

void squeeze2(char *restrict s, char const *restrict remove)
{
/* Loop through 's', only keeping chars that are not in 'remove' */
    char *out = s;

    for (; *s; ++s)
    {
        if ( !strchr(remove, *s) )
            *out++ = *s;
    }
    *out = 0;
}