由键盘任意输入一串字符,再输入一个字符和一个位置,将此字符插入在此串字符的这个位置上。如:原串为abcdef,插入字符为k,位置为2,新串为abkcdef。
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int length, i, place, cnt=0;
char* str;
char ch;
//为字符获得足够的内存空间
printf("请输入这串字符的最大长度:");
scanf("%d", &length);
str = (char*)malloc(length*sizeof(char)+1);
printf("请输入这串字符:");
scanf("%s", str);
printf("请输入你要插入的字符:");
scanf("\n%c", &ch);
printf("请输入你要插入字符的位置:");
scanf("%d", &place);
//判断字符串中字符的数量
while(str[++cnt]);
//向后移位
str[cnt+1] = '\0';
for(i=0; i<cnt-place; ++i){
str[cnt-i] = str[cnt-i-1];
}
str[place] = ch;
printf("新的字符串为:%s\n", str);
free(str);
system("pause");
return 0;
}