C语言在字符串指定位置插入新的字符串

本文介绍了如何在C语言中使用getchar和scanf函数获取用户输入,以及strcat函数实现两个字符数组的连接,最终输出合并后的字符串‘abcdef’。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 input:
 abcdef
 abc
 3

 output:
 abcabcdef
 */


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

#define  L 100

void addChar(char *,char *,int);

int main()
{
    char str1[L+1],str2[L+1],ch;
    int i=0,j=0,a;
    while ((ch=getchar())!='\n'&&ch!=EOF)
    {
        str1[i++]=ch;
    }
    str1[i]='\0';
    while ((ch=getchar())!='\n'&&ch!=EOF)
    {
        str2[j++]=ch;
    }
    str2[j]='\0';
    scanf("%d",&a);
    addChar(str1,str2,a);
    printf("%s",str1);
    return 0;
}

void addChar(char *str1,char *str2,int a)
{
    char *p1=str1;
    p1+=a;//p1指向了abcdef中的d
    strcat(str2,p1);//abc->abcdef
    *p1='\0';
    strcat(str1,str2);//abc+abcdef->abcabcdef
}

### C语言字符串指定位置插入字符串 在C语言中,由于字符串是以字符数组的形式存在,并且以空字符 `\0` 结尾,所以要在某个特定的位置插入另一段字符串并不是一件直接的事情。通常的做法是先分配足够的空间给目标字符串以便容纳新加入的内容,再移动原有数据腾出插入的空间,最后复制要插入的子字符串。 下面展示一段用于实现在已有的字符串 `destStr` 的第 `pos` 位之前插入新的字符串 `insertStr` 的代码: ```c #include <stdio.h> #include <string.h> void insert_substring(char *dest, int pos, const char *insert) { size_t dest_len = strlen(dest); size_t ins_len = strlen(insert); // Check if position is valid and within the bounds of destination string. if (pos > dest_len || pos < 0) { printf("Invalid insertion position.\n"); return; } // Allocate memory for new string with enough space to hold both strings plus null terminator. char *new_str = malloc(strlen(dest) + strlen(insert) + 1); if (!new_str) { // If allocation fails perror("Failed to allocate memory."); return; } // Copy part before insertion point into new string strncpy(new_str, dest, pos); // Append inserted string at specified location strcpy(new_str + pos, insert); // Finish by appending rest of original string after insertion strcat(new_str + pos + ins_len, dest + pos); // Print result or use it as needed; here we just demonstrate printing puts(new_str); free(new_str); // Don't forget to release allocated memory when done using it } int main() { char str[] = "HelloWorld"; const char* sub = ", "; insert_substring(str, 5, sub); // Inserting a comma followed by space between Hello and World return 0; } ``` 上述代码实现了在一个已有字符串中的任意合法位置插入一个新的字符串的功能[^1]。需要注意的是,在实际应用此函数时应当考虑边界条件以及内存管理等问题,比如当输入参数不合理时给出适当提示并安全退出操作;另外就是动态分配的内存要及时释放以免造成泄漏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值