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]; } }
问题根源
现有代码的核心逻辑是假设目标和源字符串长度完全相等:
- 将目标字符全部移到偶数下标位置,预留奇数位置给源字符;
- 把源字符依次填入奇数位置。
但当长度不等时:
- 若目标更长:源字符用完后,目标剩余的字符没有被处理,会被覆盖或丢失;
- 若源更长:代码会访问源字符串的越界位置,同时剩余的源字符无法被插入。
修复方案
改用临时缓冲区存储结果,先交替插入两个字符串的字符,直到其中一个遍历完毕,再将剩余字符直接追加到末尾。这种逻辑能兼容所有长度组合的情况:
#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
相关产品推荐
相关产品推荐

