remove duplicate from string

To remove duplicate characters from a string in C, you can follow these steps:

  1. Initialize a character array to store the input string: Begin by declaring a character array to hold the input string. For example, char str[] = "Hello World";.

  2. Find the length of the string: Use the strlen() function from the <string.h> library to determine the length of the string. For example, int len = strlen(str);.

  3. Check for duplicate characters: Iterate through each character in the string and check if it has already been encountered. To do this, you can use two nested loops. The outer loop will iterate through each character of the string, and the inner loop will compare that character with all the characters that come after it. If a duplicate character is found, it can be skipped.

  4. Remove duplicate characters: To remove a duplicate character, shift all the characters that come after it one position to the left. This can be done using a combination of the strcpy() and strcpy_s() functions from the <string.h> library.

  5. Terminate the string: After removing the duplicate characters, you need to terminate the string properly. You can do this by assigning the null character '\0' to the position after the last character in the resulting string.

Here is an example implementation of the above steps:

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

void removeDuplicates(char* str)
{
    int len = strlen(str);
    int i, j, k;

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

int main()
{
    char str[] = "Hello World";

    removeDuplicates(str);

    printf("String after removing duplicates: %s\n", str);

    return 0;
}

In this example, the removeDuplicates() function is used to remove duplicate characters from the input string. The resulting string is then printed using printf().