You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在字符数组(语句)中指定位置添加字符?含'i'转'i'+'b'+'i'需求

Solution: Insert 'b'+'i' After Every 'i' in a Char Array

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

  1. 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').
  2. Safe Memory Allocation: Using malloc, we allocate enough space for the modified string plus the required null terminator. We check if malloc succeeded to avoid crashes.
  3. 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'.
  4. Clean Up: Always remember to free the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:04:26