The "Remove Duplicates from Strings" program in C is designed to eliminate duplicate characters from a given string while preserving the order of their first occurrence. This program typically involves iterating through the string and checking if each character has already been added to a new string.
Implementation of Remove Duplicates from Strings Program
Here’s a simple implementation of this program in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: For standard input and output functions.#include <string.h>
: For string manipulation functions likestrcspn()
.
Variable Declarations:
char str[100]
: An array to hold the input string with a maximum length of 99 characters (the last character is reserved for the null terminator).char result[100]
: An array to store the resulting string without duplicates.int i, j, k = 0
: Loop counters.k
is initialized to 0 to keep track of the length of the result.
User Input:
- The program prompts the user to enter a string, which is read using
fgets()
. This function allows spaces in the input.
- The program prompts the user to enter a string, which is read using
Remove Newline Character:
- The program removes any newline character that
fgets()
might include by usingstrcspn()
.
- The program removes any newline character that
Character Iteration:
- A
for
loop iterates through each character of the input string.
- A
Duplicate Check:
- Inside the loop, another
for
loop checks if the current character (str[i]
) already exists in theresult
string. - If the character is found,
found
is set to 1, indicating that it is a duplicate.
- Inside the loop, another
Add Unique Characters:
- If the character is not found (i.e.,
found
remains 0), it is added to theresult
string at indexk
, andk
is incremented.
- If the character is not found (i.e.,
Null-Termination:
- After processing all characters, the
result
string is null-terminated to make it a valid string.
- After processing all characters, the
Display Results:
- Finally, the program prints the modified string with duplicates removed.
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter a string when prompted.
Example Input/Output
Input:
Output:
Conclusion
The "Remove Duplicates from Strings" program in C demonstrates string manipulation and basic data handling techniques. It reinforces the understanding of loops, conditionals, and arrays. This type of program can be modified to include additional functionality, such as removing duplicates while ignoring case sensitivity or counting the number of duplicates removed.