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

C语言中使用数组实现字符串间字符插入的问题求助

字符串交替插入功能修复:解决长度不等时的拼接错误

问题场景

我需要实现将源字符串的字符逐个插入到目标字符串的字符间隙中,但当前代码仅在两个字符串长度相等时能正常工作,长度不等时无法得到预期结果:

  • 目标apple + 源fruit:输出afprpuliet(正确);
  • 目标plane + 源yes:预期pyleasne,当前代码无法实现;
  • 目标fly + 源train:预期ftlryain,当前代码无法实现。

现有代码

#include <stdio.h>
#include <string.h>

#define DESTSIZE 100
#define SOURCESIZE 20

int main(void)
{
    char destination [DESTSIZE], source [SOURCESIZE];
    printf("enter destinantion string for strinsert: ");
    scanf("%s", destination);
    printf("enter source string for strinsert: ");
    scanf("%s", source);
    strinsert(destination, source);
    printf("after strinsert, destination string is %s\n", destination);
    
    return 0;
}

void strinsert(char destination[], char source [])
{
    int dest_len = strlen(destination);
    for (int i = dest_len - 1; i >= 0; i--) {
        destination[2 * i] = destination[i];
    }
    for (int i = 0; i < dest_len; i++) {
        destination[2 * i + 1]= source[i];
    }
}

问题根源

现有代码的核心逻辑是假设目标和源字符串长度完全相等:

  1. 将目标字符全部移到偶数下标位置,预留奇数位置给源字符;
  2. 把源字符依次填入奇数位置。

但当长度不等时:

  • 若目标更长:源字符用完后,目标剩余的字符没有被处理,会被覆盖或丢失;
  • 若源更长:代码会访问源字符串的越界位置,同时剩余的源字符无法被插入。

修复方案

改用临时缓冲区存储结果,先交替插入两个字符串的字符,直到其中一个遍历完毕,再将剩余字符直接追加到末尾。这种逻辑能兼容所有长度组合的情况:

#include <stdio.h>
#include <string.h>

#define DESTSIZE 100
#define SOURCESIZE 20

void strinsert(char destination[], const char source[]);

int main(void)
{
    char destination[DESTSIZE], source[SOURCESIZE];
    printf("enter destinantion string for strinsert: ");
    scanf("%s", destination);
    printf("enter source string for strinsert: ");
    scanf("%s", source);
    strinsert(destination, source);
    printf("after strinsert, destination string is %s\n", destination);
    
    return 0;
}

void strinsert(char destination[], const char source[])
{
    int dest_len = strlen(destination);
    int src_len = strlen(source);
    char temp[DESTSIZE];
    int dest_idx = 0, src_idx = 0, temp_idx = 0;

    // 交替插入两个字符串的字符
    while (dest_idx < dest_len && src_idx < src_len) {
        temp[temp_idx++] = destination[dest_idx++];
        temp[temp_idx++] = source[src_idx++];
    }

    // 追加目标字符串剩余的字符
    while (dest_idx < dest_len) {
        temp[temp_idx++] = destination[dest_idx++];
    }

    // 追加源字符串剩余的字符
    while (src_idx < src_len) {
        temp[temp_idx++] = source[src_idx++];
    }

    // 添加字符串结束符,确保是合法的C字符串
    temp[temp_idx] = '\0';
    // 将结果拷贝回目标数组
    strcpy(destination, temp);
}

测试验证

  • 目标plane + 源yes:输出pyleasne(符合预期);
  • 目标fly + 源train:输出ftlryain(符合预期);
  • 目标apple + 源fruit:输出afprpuliet(保持正确)。

内容的提问来源于stack exchange,提问作者DomesticPotato

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:20:30