Complementary task for topic: 7

M Nemeth · 2023-08-29 15:21:04.623218'

Strings: Remove Duplicate Characters from String

Strings: Remove Duplicate Characters from String

Create a C program that reads a string from the user and removes any duplicate characters from it. The program should display the modified string as the output.

Hint: Use a character array (char array) to store the string.
Prompt the user to enter a string.
Remove any duplicate characters from the string.
Display the modified string as the output.

Solution
#include 
#include 

int main() {
    char inputString[200];
    char resultString[200];
    int resultIndex = 0;

    printf("Enter a string: ");
    fgets(inputString, sizeof(inputString), stdin);
    inputString[strcspn(inputString, "\n")] = '\0'; // Remove the trailing newline

    // Remove duplicate characters
    for (int i = 0; inputString[i] != '\0'; i++) {
        bool isDuplicate = false;

        for (int j = 0; j < resultIndex; j++) {
            if (inputString[i] == resultString[j]) {
                isDuplicate = true;
                break;
            }
        }

        if (!isDuplicate) {
            resultString[resultIndex] = inputString[i];
            resultIndex++;
        }
    }

    resultString[resultIndex] = '\0'; // Null-terminate the result string

    printf("Modified string: %s\n", resultString);

    return 0;
}



Explanation
The program defines a character array (char array) inputString to store the input string, a character array resultString to store the modified string, and an integer variable resultIndex to keep track of the index in the resultString array.

The user is prompted to enter a string using printf() and fgets(). The fgets() function is used to read the entire line, and strcspn() is used to remove the trailing newline character (\n).

The program then iterates through each character in the inputString and checks if it is a duplicate character. It does this by comparing each character with the characters already present in the resultString array.

If the character is not a duplicate, it is added to the resultString array at the current resultIndex, and resultIndex is incremented.

The resulting resultString contains the modified string with duplicate characters removed.
< < previous    next > >