已知输入字符串,要求输入指定要删除已知字符串中的具体字符。
比如说:已知字符串为thankyou,指定输入4,则会删除原字符串中的k,得到thanyou
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define N 20
void func(char a[],char b[],int n)
{
int i,k = 0;
for (i = 0; a[i] != '\0'; i++)
{
if (i != n)
{
b[k++] = a[i];
}
}
b[k] = '\0';
}
int main()
{
system("CLS");
int n;
char str1[N],str2[N];
printf("Please enter a string :\n");
gets(str1);
int i = 0,count = 0;
while(str1[i] != '\0')
{
i++;
count++;
}
printf("Enter the position of the string deleted :\n");
scanf("%d",&n);
if((n < 0)||(n >= count))
{
printf("n must larger or equal to 0 and less than the size of input number \n");
getch();
return -1;
}
func(str1,str2,n);
printf("The new string is : %s",str2);
getch();
return 0;
}
结果如下:
我在程序中添加了一项if判断,限定了输入元素n的范围,n必须>=0且<=元素的总个数。
如果输入的n<0||n>count,会返回-1,结束程序。运行如下:
或者: