两个功能孤立地工作,但不是一起工作

时间:2014-10-28 18:35:02

标签: strcpy

我有两个函数rmdup和rmvow,当我单独运行这些函数时它们工作得很好,但当它们在程序中一起工作时它们根本不工作?

int rmdup ( char name[] ) 
{

  char nodup[20] = {''\0''};
  int l = strlen(name);
  int i = 0, j, k = 0;

  while ( i < l ) 
  {
    j = i + 1;

    if ( name[i] == name[j] ) 
    {
      nodup[k] = name[i];
      i+2;
      while(nodup[k] == name[i]) 
      {
        i++;
      }
      k++;
    }
    else 
    {
      i++;
    }

    nodup[k] = ''\0'';
  }

  strcpy(name, nodup);
}

上述工作是孤立的,如下所述。

int rmvow ( char name[]  ) 
{
  char novow[20] = {''\0''};
  int l = strlen(name);
  int i = 0, j = 0;

  while ( i < l ) 
  {
    if ( name[i] == ''a'' || 
         name[i] == ''e'' ||
         name[i] == ''i'' ||
         name[i] == ''o'' ||
         name[i] == ''u'' ) 
    {
      i++;
    }
    else 
    {
      novow[j] = name[i];
      i++;
      j++;
    }

    novow[j] = ''\0'';
  }

  strcpy(name, novow);
}

1 个答案:

答案 0 :(得分:0)

以下更正和完整的代码输出:

aabbccddeeff
abcdef
bcdf

这似乎是正确的。唯一的更正是i += 2中的rmdup()和有效的字符常量。在没有任何其他信息的情况下编译为C代码。

#include <stdio.h>
#include <string.h>

int rmdup ( char name[] ) ;
int rmvow ( char name[] ) ;

int main(void) 
{
    char test[] = "aabbccddeeff" ;

    printf( "%s\n", test ) ;
    rmdup( test ) ;

    printf( "%s\n", test ) ;
    rmvow( test ) ;

    printf( "%s\n", test ) ;

    return 0;
}

int rmdup ( char name[] ) 
{

  char nodup[20] = {'\0'};
  int l = strlen(name);
  int i = 0, j, k = 0;

  while ( i < l ) 
  {
    j = i + 1;

    if ( name[i] == name[j] ) 
    {
      nodup[k] = name[i];
      i+=2;
      while(nodup[k] == name[i]) 
      {
        i++;
      }
      k++;
    }
    else 
    {
      i++;
    }

    nodup[k] = '\0';
  }

  strcpy(name, nodup);
}

int rmvow ( char name[]  ) 
{
  char novow[20] = {'\0'};
  int l = strlen(name);
  int i = 0, j = 0;

  while ( i < l ) 
  {
    if ( name[i] == 'a' || 
         name[i] == 'e' ||
         name[i] == 'i' ||
         name[i] == 'o' ||
         name[i] == 'u' ) 
    {
      i++;
    }
    else 
    {
      novow[j] = name[i];
      i++;
      j++;
    }

    novow[j] = '\0';
  }

  strcpy(name, novow);
}

然而,代码是危险的,因为没有防止溢出novownodup数组的保护。两者都没必要;在这两种情况下,您都可以将数据直接写回name,因为目标索引总是&lt; =源索引。

int rmdup ( char name[] ) 
{

  int l = strlen(name);
  int i = 0, j, k = 0;

  while ( i < l ) 
  {
    j = i + 1;

    if ( name[i] == name[j] ) 
    {
      name[k] = name[i];
      i+=2;
      while(name[k] == name[i]) 
      {
        i++;
      }
      k++;
    }
    else 
    {
      i++;
    }

    name[k] = '\0';
  }
}

int rmvow ( char name[]  ) 
{
  int l = strlen(name);
  int i = 0, j = 0;

  while ( i < l ) 
  {
    if ( name[i] == 'a' || 
         name[i] == 'e' ||
         name[i] == 'i' ||
         name[i] == 'o' ||
         name[i] == 'u' ) 
    {
      i++;
    }
    else 
    {
      name[j] = name[i];
      i++;
      j++;
    }

    name[j] = '\0';
  }
}