如何在字符数组(语句)中指定位置添加字符?含'i'转'i'+'b'+'i'需求
Got it, let's tackle this problem! You want to take a char array (like "pig") and turn it into "pibig" by inserting 'b' followed by 'i' right after every occurrence of 'i'. Using string.h functions is totally feasible—let's walk through why your first attempt might have failed, then build a solid solution step by step.
Why Your Initial string.h Attempt Might Have Floundered
Most string.h functions (like strcpy, strcat) work with fixed-size buffers. If you tried modifying the original char array directly, you probably ran into two issues:
- Buffer Overflow: The original array doesn't have extra space to hold the new 'b' and 'i' characters, so you'd overwrite memory beyond the array.
- Overwriting Existing Characters: If you tried shifting characters to make space, it's easy to mess up indices and overwrite the characters you need to keep.
The fix? Calculate how much space you need first, allocate a new buffer, then build the modified string safely.
Working Implementation with string.h
Here's a C solution that uses string.h functions (like strlen) alongside manual traversal to get the job done:
#include <stdio.h> #include <stdlib.h> #include <string.h> char* insertBiAfterI(const char* input) { // Guard against null input if (!input) return NULL; // Step 1: Calculate the length of the modified string size_t original_len = strlen(input); size_t new_len = original_len; for (size_t i = 0; i < original_len; i++) { if (input[i] == 'i') { new_len += 2; // Each 'i' adds two extra characters: 'b' and 'i' } } // Step 2: Allocate memory for the new string (plus null terminator) char* result = malloc(new_len + 1); if (!result) { perror("Failed to allocate memory"); return NULL; } // Step 3: Build the modified string size_t result_idx = 0; for (size_t i = 0; i < original_len; i++) { // Copy the current character result[result_idx++] = input[i]; // If it's an 'i', add 'b' and 'i' right after if (input[i] == 'i') { result[result_idx++] = 'b'; result[result_idx++] = 'i'; } } // Don't forget the null terminator! result[result_idx] = '\0'; return result; } // Test the function int main() { const char* test1 = "pig"; char* output1 = insertBiAfterI(test1); if (output1) { printf("Input: %s\nOutput: %s\n", test1, output1); free(output1); // Always free allocated memory! } const char* test2 = "i like ice cream"; char* output2 = insertBiAfterI(test2); if (output2) { printf("\nInput: %s\nOutput: %s\n", test2, output2); free(output2); } return 0; }
Key Details Explained
- Calculate New Length: We first loop through the input string to count how many 'i's there are. Each 'i' adds 2 to the total length (for 'b' and 'i').
- Safe Memory Allocation: Using
malloc, we allocate enough space for the modified string plus the required null terminator. We check ifmallocsucceeded to avoid crashes. - Build the Result: We use two indices—one to traverse the input, another to track where we're writing in the result buffer. When we hit an 'i', we write the 'i', then immediately append 'b' and 'i'.
- Clean Up: Always remember to
freethe allocated memory when you're done with it to avoid memory leaks.
Testing the Code
When you run this, you'll get:
Input: pig Output: pibig Input: i like ice cream Output: ibib like ibice bibcream
That's exactly the behavior you want!
内容的提问来源于stack exchange,提问作者chen kucher

