求C语言字母转数字编码程序实现方案(支持自定义映射)
Hey there! Let's tackle this encoding problem step by step, using a "dictionary-like" approach that's easy to tweak later—perfect for your needs. Since C doesn't have a native dictionary type, we'll use an array to simulate key-value pairs (where the "key" is the character, and the "value" is its corresponding code). This way, you can update mappings in one place without rewriting tons of if statements.
Step 1: Understand the Array Mapping Concept
In C, characters are just ASCII integers under the hood. So we can create an array where:
- The index of the array is the ASCII value of the character (e.g.,
'a'is 97,' 'is 32) - The value stored at that index is the code we want to map to (e.g.,
1for'a',11111for space)
This acts exactly like a dictionary—look up the character's ASCII index, get the code instantly.
Step 2: Full Implementation Code
Here's a complete, commented program that does exactly what you need. I'll break down each part after the code:
#include <stdio.h> #include <ctype.h> // For tolower() function, to handle uppercase letters int main() { // 1. Initialize our "dictionary" array: size 256 covers all ASCII characters int char_to_code[256] = {0}; // Initialize all values to 0 by default // 2. Map lowercase letters to their alphabet positions (a=1, b=2, ..., z=26) for (int i = 'a'; i <= 'z'; i++) { char_to_code[i] = i - 'a' + 1; // Example: 'a' - 'a' +1 = 0+1=1, 'b'-'a'+1=1+1=2, etc. } // 3. Map uppercase letters to the same codes as lowercase (optional but useful) for (int i = 'A'; i <= 'Z'; i++) { char_to_code[i] = i - 'A' + 1; // Alternatively, you could convert input to lowercase first—either works! } // 4. Map space to 11111 as required char_to_code[' '] = 11111; // 5. Open input and output files FILE *input_file = fopen("input.txt", "r"); FILE *output_file = fopen("output.txt", "w"); // Check if files opened successfully (critical to avoid crashes!) if (input_file == NULL || output_file == NULL) { printf("Error opening files!\n"); return 1; // Exit with error code } // 6. Read each character from input and write corresponding code to output char current_char; int first_code = 1; // To avoid extra space at the start of output while ((current_char = fgetc(input_file)) != EOF) { int code = char_to_code[(unsigned char)current_char]; // Only write codes for characters we have mapped (skip unknown chars) if (code != 0) { if (!first_code) { fputc(' ', output_file); // Add space before subsequent codes } fprintf(output_file, "%d", code); first_code = 0; // After first code, we need spaces before others } } // 7. Clean up: close files fclose(input_file); fclose(output_file); printf("Encoding completed successfully!\n"); return 0; }
Step 3: How to Modify Mappings Easily
This approach makes changing mappings a breeze:
- Change letter codes: If you want
ato map to10instead of1, just update the loop:
Or override individual letters:char_to_code[i] = (i - 'a' + 1) * 10; // Makes a=10, b=20, ..., z=260char_to_code['x'] = 999; // x now maps to 999 instead of 24 - Change space code: Just update this line:
char_to_code[' '] = 99999; // Space now maps to 99999 instead of 11111 - Add new mappings: Want to map
!to00000? Just add:char_to_code['!'] = 0; // Or any number you want
Step 4: Key Notes for Your C Foundation
- File Handling: Always check if
fopen()returnsNULL—this happens if the input file doesn't exist or you don't have permission to write the output file. - ASCII Values: Characters like
'a'are just numbers (97 in ASCII), so we can use them as array indices safely. - Uppercase Handling: The code above maps uppercase letters directly, but you could also convert input to lowercase first with
tolower(current_char)(just make sure to include<ctype.h>). - Unknown Characters: The code skips any characters not in our mapping (since their code is 0). You can modify this to write a default code (like
0) if needed.
内容的提问来源于stack exchange,提问作者Sepsi Zoltán

