插入字符的几种方法

一、利用数组移位

#include <stdio.h>
#include <string.h>
int main()
{
 int num;
 char ch;
 char str[20] = {0};
 int length, i;
 
 printf("please input \n");
 scanf("%s%d %c", str, &num, &ch);    //整形和字符间要空格 即%d  %c之间空格
 length = strlen(str);
 
 for (i = 0; i < length - num + 1; i++)             //循环 length-num+1
 {
  str[length - i] = str[length - i - 1];
 }

    str[num - 1] = ch;
 printf("%s\n",str);
 return 0;
}
二、利用函数 strncat(连接)和strncpy(复制覆盖)
#include <stdio.h>
#include <string.h>
int main()
{
 char str[20] = {0};
 char ptr[20] = {0};
 char ch;
 int  num;
 printf("please input \n");
 scanf("%s%d %c", str, &num, &ch);

 /*strncpy(ptr, str, num - 1);
 strncpy(ptr + num - 1, &ch, 1);                                         //第一种用复制
 strcpy(ptr + num , str + num - 1);*/
 
 strncat(ptr, str ,num - 1);
 strncat(ptr, &ch, 1);
 strcat(ptr, str + num - 1);                                                    //第二种用连接字符串,从最后一个开始连接
 printf("%s\n", ptr);
 return 0;
}
三、利用指针
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
 char *p, *q;
 p  = (char *)malloc(sizeof(char) * 100);
 if (NULL == p)
 {
  printf("malloc failure\n");
 }
 q  = (char *)malloc(sizeof(char) * 100);
 if (NULL == q)
 {
  printf("malloc failure\n");
 }
 int num;
 char ch;
 printf("please input :\n");
 scanf("%s %d %c", p, &num, &ch);
 strncpy( q, p, num - 1);
 *(q + num - 1) = ch;
 strcpy( q + num, p + num -1);
 printf("%s\n", q);
 free(p);
 free(q);
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值