Home > other >  Sorted string after removing the same characters not working right
Sorted string after removing the same characters not working right

Time:02-16

Overall the code is working except one part. The code first outputs sorted string in alphabetical order. Then the repeated characters are removed so each letter is displayed just once. My problem here is when I input "datastructures" it displays acdersttu, but instead I should have acderstu, which means with only one t. Where is the problem? My code:

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

int main ()
{
    char str[100];
    int freq[256] = {0};
    char temp;
    int i, j, k;
    printf("\nEnter the string: ");
    scanf("%s",str);

    int n = strlen(str);
    for (i = 0; i < n; i  ) {
        for (j = i 1; j < n; j  ) {
            if (str[i] > str[j]) {
                    temp = str[i];
                    str[i] = str[j];
                    str[j] = temp;
            }
        }
    }
    printf("The sorted string is: %s", str);

    for(i = 0; i < n; i  ) 
        for(j = i   1; str[j] != '\0'; j  )
            if(str[j] == str[i])  
                for(k = j; str[k] != '\0'; k  )
                    str[k] = str[k   1];
    
    printf("\nThe sorted string after removing same characters is: %s ", str);
    return 0;
}

CodePudding user response:

The rule which you defined is applicable only when there are 2 repeated characters, since 3 t's are there it is not working fine. Below code is the change, for the second loop.

for(i = 0; i < n; i  )
    for(j = i   1; str[j] != '\0'; j  )
        if(str[j] == str[i]){
            for(k = j; str[k] != '\0'; k  )
                str[k] = str[k   1];
            j=j-1;
        }
       

printf("\nThe sorted string after removing same characters is: %s ", str);
return 0;
  • Related