简体   繁体   中英

C program to remove all repeated characters in a string

I want to remove all the repeated characters from a string. For example, if I have:

"aapuroo"

I want the result to be

apuro

but it shows

apuroo

what is my mistake here?I am a beginer pardon my mistakes

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

int main()
{
    char str[100];
    int i,j,k,n;
    gets(str);

    n = strlen(str);

    for(i=0; i<n; i++)
    {

        for(j=i+1; j<n;j++)
        {
             if(str[i] == str[j])
             {
                 str[j] = str[j+1];
             }

        }
    }

    puts(str);

    return 0;
}

The approach is invalid. Consider a string like char str[] = "111"; .

So in these loops

for(i=0; i<n; i++)
{

    for(j=i+1; j<n;j++)
    {
         if(str[i] == str[j])
         {
             str[j] = str[j+1];
         }

    }
}

str[0] is equal tp '1' . str[1] is also equal to '1' . So str[1] is substituted for str[2] that is also equal tp '1' . As a result you will get that the array contains the string "11"

Moreover the inner loop processes not only adjacent repeated characters but all duplicated characters in the string.

Pay attention to that the function gets is an unsafe function and is not supported by the C Standard any more. Use instead the standard function fgets .

The program can look the following way

#include <stdio.h>

int main()
{
    enum { N = 100 };
    char str[N];

    fgets( str, N, stdin );

    for ( size_t i = 0, j = 0;  str[i] != '\0'; )
    {
        if ( str[++i] != str[j] && str[i] != '\n' ) 
        {
            if ( i != ++j ) str[j] = str[i];
        }           
    }

    puts( str );

    return 0;
}

If to enter the string "aapuroo" then the program output will be

apuro

The subexpression str[i] != '\\n' used in the if statement is present because the function fgets can append the new line character to the entered string. So this subexpression is used to exclude the new line character from the result string. Or you could before the loop to remove this character.

When you find a repeated character, you need to shift the rest of the string to the left, filling the last byte with a zero. As for your code, you just duplicate the [j+1] character and then, in your case, exiting since you are at the end of the string.

#include <stdio.h>

int main()
{
  char str[100];
  // this programm is created by chandan pradhan
  gets(str);
  for ( size_t i = 0, j = 0;  str[i] != NULL;)
  {
    if ( str[++i] != str[j] && str[i] != '\n' ) 
    {
      if ( i != ++j ) 
        str[j] = str[i];
    }
  }
  puts( str );
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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