Search code examples
cstringcharacternon-repetitive

How to remove duplicate characters that repeats many times at the end of a string in C language?


I am trying to learn how to work with strings in C and I have this problem, I need to reverse a string and print it without any repetitive characters. I have tried the code below and it worked but if I add many repetitive characters of the same type it does not work.

For example: dodon - nodod - nod but with the string dodoneeee - eeeenodod - eenod. The e is still repeated.

The code is below:

#include <stdio.h>
#include <string.h>
int main(){
char word[20];
char reverse_string[20];
printf("type a string: ");
scanf("\n%s", word);       
for(int i = strlen(word)-1; i>=0; i--)
{
    // 5 - 5 = 0
    // 5- 4 = 1
    // 5- 3 = 2
    // 5- 2 = 3
    // 5- 1 = 4
    // 5- 0 = 5
    reverse_string[(strlen(word)-1)-i] = word[i];         
  }
  printf("%s\n",reverse_string);     
 for(int i = 0; i< strlen(reverse_string)-1;i++)
 {
    for(int j = i+1; reverse_string[j] != '\0';j++)
    {
        if(reverse_string[j] == reverse_string[i])
        {
            for(int k = j; reverse_string[k] != '\0'; k++)
            {
                //printf("%c\n", reverse_string[k+1]);
                reverse_string[k] = reverse_string[k + 1];
            }                
        }           
    }        
  }
   printf("%s\n", reverse_string);    
return 0;
}

Solution

  • Here is your code. The main problem was the j++. You must stay in the same j until reverse_string[j] != reverse_string[i]. The second problem was that you did not terminated the string.

    #include <stdio.h>
    #include <string.h>
    int main()
    {
    char word[20];
    char reverse_string[20];
    printf("type a string: ");
    scanf("%s", word);
    
    for(int i = strlen(word)-1; i>=0; i--)
    {
        // 5 - 5 = 0
        // 5- 4 = 1
        // 5- 3 = 2
        // 5- 2 = 3
        // 5- 1 = 4
        // 5- 0 = 5
        reverse_string[(strlen(word)-1)-i] = word[i];
      }
      reverse_string[strlen(word)] = '\0'; //add string termination
      printf("%s\n",reverse_string);
    
    
     for(int i = 0; i< strlen(reverse_string)-1;i++)
     {
        for(int j = i+1; reverse_string[j] != '\0';) //j++ was moved. 
        {
            if(reverse_string[j] == reverse_string[i])
            {
    
                for(int k = j; reverse_string[k] != '\0'; k++)
                {
                    //printf("%c\n", reverse_string[k+1]);
                    reverse_string[k] = reverse_string[k + 1];
                }
    
            }
            else
                j++; //j++ was moved here 
        }
      }
       printf("%s\n", reverse_string);
    
    return 0;
    }