如何在C语言中仅使用数组、循环与条件语句移除字符数组中的所有重复字符
How to Remove All Duplicate Characters from a Character Array in C
Let's break down what's wrong with your current code first, then walk through a correct implementation that meets your requirements (only arrays, loops, if/else, no pointers).
Issues with Your Current Code
- Input Handling: Using
scanf("%c", &c[i])for 10 iterations will read whitespace (like newlines) if your input is shorter than 10 characters, which messes up your data. You also don't track the actual length of the input string. - Duplicate Tracking Logic: Your nested loop only marks
com[i]whenc[i] == c[j], but this misses cases where the same character repeats in later positions (e.g., the second 'a' in "aabccdee" won't be marked). Thecntvariable also counts duplicate pairs instead of unique duplicate characters, leading to incorrect results. - Result Array Construction: The final loop that builds
resulthas backwards logic—you're trying to exclude duplicate characters but the nested loops don't correctly filter them, leading to garbage or incorrect output.
Correct Implementation
The core idea is to first count how many times each character appears in the input, then collect only the characters that appear exactly once. Here's how to do it:
#include <stdio.h> int main() { // Define arrays with enough space (adjust if needed; 100 is safe for most cases) char input[100]; int char_count[256] = {0}; // Tracks occurrence count of each ASCII character char result[100] = {0}; int input_len = 0; int result_idx = 0; // Step 1: Read input string and get its length printf("Enter the character string: "); // Read until newline (avoids reading extra whitespace) while ((input[input_len] = getchar()) != '\n') { input_len++; } // Step 2: Count occurrences of each character for (int i = 0; i < input_len; i++) { // Convert char to its ASCII value to index into char_count char_count[(unsigned char)input[i]]++; } // Step 3: Build result array with characters that appear exactly once for (int i = 0; i < input_len; i++) { if (char_count[(unsigned char)input[i]] == 1) { result[result_idx] = input[i]; result_idx++; } } // Step 4: Output the result printf("Result: %s\n", result); return 0; }
How This Works
- Input Handling: We use
getchar()to read each character until a newline, which lets us track the actual length of the input without extra whitespace. - Counting Characters: The
char_countarray (size 256 to cover all ASCII characters) keeps track of how many times each character appears. For every character in the input, we increment its corresponding index inchar_count. - Building the Result: We loop through the input again, and only add characters to the
resultarray if their count inchar_countis exactly 1 (meaning they don't have duplicates). - Output: The result array is printed as a string (since we initialized it to 0, it's null-terminated correctly).
Testing this with your example input aabccdee:
- The count for 'a' is 2, 'b' is 1, 'c' is 2, 'd' is 1, 'e' is 2.
- The result array will collect 'b' and 'd', so the output is
bd—exactly what you need.
If you specifically need to use fixed-size arrays (like your original 10-length arrays), you can modify the code to cap the input length at 9 (leaving space for the null terminator):
#include <stdio.h> int main() { char input[10] = {0}; int char_count[256] = {0}; char result[10] = {0}; int input_len = 0; int result_idx = 0; printf("Enter up to 9 characters: "); // Read up to 9 characters or until newline while (input_len < 9 && (input[input_len] = getchar()) != '\n') { input_len++; } // Count occurrences for (int i = 0; i < input_len; i++) { char_count[(unsigned char)input[i]]++; } // Build result for (int i = 0; i < input_len; i++) { if (char_count[(unsigned char)input[i]] == 1) { result[result_idx] = input[i]; result_idx++; } } printf("Result: %s\n", result); return 0; }
内容的提问来源于stack exchange,提问作者Hongwon Lim
相关产品推荐
相关产品推荐

