Skip to content

Instantly share code, notes, and snippets.

@novnan
Last active January 3, 2016 05:39
Show Gist options
  • Save novnan/8416981 to your computer and use it in GitHub Desktop.
Save novnan/8416981 to your computer and use it in GitHub Desktop.
/* 输入一个字符串,存放在字符数组中,然后将某个字符插入到该字符串的某个位置
要求考虑输入的插入位置可能小于0(在首位插入),或大于字符串长度的情况(在尾部插入)等情况*/
#include <stdio.h>
#include <string.h>
void main()
{
char s[256];
char ch;
int i, len, position;
printf("输入字符串:");
//gets(s);
scanf("%s", s); //不行,为什么?
getchar();
printf("输入要插入的字符:");
ch = getchar();
printf("要插到第几个字符:");
scanf("%d", &position);
len = strlen(s); //计算字符串的长度
if(position <= len)
{
for(i = len - 1; i >= position; i--)
{
s[i + 1] = s[i]; // 将指定位置以后的字符分别往后移一个位置
}
s[position] = ch;
s[len + 1] = '\0'; //最后一个字符要赋为'\0'
}
else
{ // position > len
s[len] = ch;
s[len + 1] = '\0';
}
printf("插入后的字符串是:%s\n", s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment