删除字符串中的指定字符

已知输入字符串,要求输入指定要删除已知字符串中的具体字符。

比如说:已知字符串为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,结束程序。运行如下:

或者:



  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值