一、利用数组移位
#include <stdio.h>
#include <string.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之间空格
{
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];
}
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>
#include <string.h>
int main()
{
char str[20] = {0};
char ptr[20] = {0};
char ch;
int num;
{
char str[20] = {0};
char ptr[20] = {0};
char ch;
int num;
printf("please input \n");
scanf("%s%d %c", str, &num, &ch);
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>
#include <string.h>
#include <stdlib.h>
int main()
{
char *p, *q;
{
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);
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);
*(q + num - 1) = ch;
strcpy( q + num, p + num -1);
printf("%s\n", q);
free(p);
free(q);
return 0;
}
free(p);
free(q);
return 0;
}