Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorted string after removing the same characters not working right

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading