What is the method to remove duplicate characters in the C programming language?

The method of deleting duplicate characters in C language can be achieved through the following steps:

  1. Create a new string to store the result after removing duplicate characters.
  2. Iterate through each character of the original string and check if the character already exists in the new string.
  3. If the character does not exist in the new string, then add the character to the new string.
  4. The final output will be the result of removing any duplicate characters.

Here is a simple example code in C language:

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

int main() {
    char str[100];
    char result[100];
    int i, j, flag;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove duplicate characters
    for (i = 0; i < strlen(str); i++) {
        flag = 0;
        for (j = 0; j < strlen(result); j++) {
            if (str[i] == result[j]) {
                flag = 1;
                break;
            }
        }
        if (!flag) {
            result[strlen(result)] = str[i];
        }
    }

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

    return 0;
}

This code loops through the original string, compares each character one by one, and adds non-repeating characters to a new string, ultimately outputting the result after removing duplicates.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds