使用C指针颠倒字符串

使用C指针颠倒字符串。

例如: "Welcome to India" 变为"India to Welcome"

Reverse a string using C pointers
Ex: "Welcome to India" to "India to Welcome"

算法及例子如下:

先颠倒整个字符串,然后颠倒单个单词。

Welcome to India

after step 1 => aidnI ot emocleW
after step 2 => India to Welcome

Algorithm is:
1. Reverse the whole string.
2. Reverse the individual words.

For example:
Welcome to India
after step 1 => aidnI ot emocleW
after step 2 => India to Welcome

#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
void reverse_string(char* str,char * end)
{
	char c;
	while (str<end)
	{
		c = *str;
		*str = *end;
		*end = c;
		str++;
		end--;
	}
}
void reverse_word()
{
	char str[MAX_LEN];
	printf("input the string:");
	fgets(str,MAX_LEN,stdin);//读入的字符串中最后包含读到的换行符 以及结束符
	int len = strlen(str);
	
	char*start = str,*end = str + len - 2;
	str[len - 1] = '\0';//将结尾之前的换行符置为结束符
	reverse_string(start,end);
	start = strtok(str," ");
	while (start)
	{
		end = start+strlen(start)-1;
		reverse_string(start,end);
		start = strtok(NULL," ");
	}
	for (int i = 0;i<len-1;i++)
	{
		printf("%c",str[i]);
	}
	printf("\n");
}
int main()
{
	reverse_word();
	return 1;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值