删除字符串中指定位置的字符

比如说删除字符串certainly中的第5个字符i,变成certanly。

具体实现如下:

首先:主函数框架如下:

#include <stdio.h>
#include <windows.h>
#include <conio.h>
#define N 20
void proc(char a[], char b[], int n);
void main()
{
	char str1[N], str2[N];
	int n;
	system("CLS");
	printf("Enter the string !\n");
	gets(str1);
	printf("Enter the position of the string deleted !\n");
	scanf("%d",&n);
	proc(str1,str2,n);
	printf("The new string is :%s \n",str2);

	getch();
}
通过调用proc子函数实现。

子函数中a[ ]表示输入的原字符串。(可以用const修饰)

子函数中b[ ]表示删除字符后得到的字符串。

n表示删除字符的具体位置。

proc函数的具体实现如下:

void proc(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';
}
也可以这样
void proc(char a[], char b[], int n){
	int len = strlen(a);
	int i;
	for (i = 0; i < len; i++)
	{
		if ( i < n)
		{
			b[i] = a[i];
		}
		else
		{
			b[i] = a[i+1];
		}
	}
	b[len - 1] = '\0';
}
结果显示如下:

完整代码如下:

#include <stdio.h>
#include <windows.h>
#include <conio.h>
#define N 20
void proc(char a[], char b[], int n);
void main()
{
	char str1[N], str2[N];
	int n;
	system("CLS");
	printf("Enter the string !\n");
	gets(str1);
	printf("Enter the position of the string deleted !\n");
	scanf("%d",&n);
	proc(str1,str2,n);
	printf("The new string is :%s \n",str2);

	getch();
}
void proc(char a[], char b[], int n){
	int len = strlen(a);
	int i;
	for (i = 0; i < len; i++)
	{
		if ( i < n)
		{
			b[i] = a[i];
		}
		else
		{
			b[i] = a[i+1];
		}
	}
	b[len - 1] = '\0';
}
实现起来还是很简单的^_^



  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值