试编一函数:将字符串中第1个到第m个字符,平移到字符串的最后,把第m+1到最后的字符移到字符串的前部

本文介绍了一个C语言程序,该程序能够实现字符串的特定操作,包括字符交换及子串反转等功能。通过对字符串不同部分的操作,展示了如何使用指针和循环来完成这些任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例:char ch[]="international";
i n t e r n a t i o n a l 变为 r n a t i o n a l i n t e

(1)将ch[0]个到第ch[4]字符与最后交换
        l a n o r n a t i e t n i
(2)反转ch[9]到ch[12]的部分
        l a n o r n a t i
i n t e
(3)反转ch[0]到ch[8]的部分
        i t a n r o n a l i n t e
(4)反转ch[0]到ch[4]的部分
        r n a t i o n a l i n t e
#include <stdio.h>
#include <string.h>
void fun (char * ptr,int m)
{
	int lenth=strlen(ptr)-1;
	int i;
	int j;
	//将第1个到第m字符与最后交换
	for(i=0,j=lenth;i<m;i++)
	{
		
		char tmp=ptr[i];
		ptr[i]=ptr[j];
		ptr[j]=tmp;
		j--;
	}

	//反转lenth-m+1到lenth的部分
	for(i=lenth-m+1,j=lenth;i < j;i++,j--)
	{
		char tmp=ptr[i];
		ptr[i]=ptr[j];
		ptr[j]=tmp;
		
	}

	//反转0到lenth-m的部分
	for(i=0,j=lenth-m; i < j;i++,j--)
	{

		char tmp=ptr[i];
		ptr[i]=ptr[j];
		ptr[j]=tmp;
	}

	//反转0到lenth-m-m的部分
	for(i=0,j=lenth-m-m;i < j;i++,j--)
	{
		char tmp=ptr[i];
		ptr[i]=ptr[j];
		ptr[j]=tmp;
	}
}

int main(int argc, char const *argv[])
{
	char ch[50]={0};
	int lenth;
	int m;
	printf("please input character\n");
	scanf("%s",ch);
	printf("please input m\n");
	scanf("%d",&m);
	fun(ch,m);
	printf("%s\n",ch);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lmory233

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值