现在的位置: 首页 > 综合 > 正文

10 翻转句子中单词的顺序。

2018年05月02日 ⁄ 综合 ⁄ 共 677字 ⁄ 字号 评论关闭
/*
第 10  题
翻转句子中单词的顺序。
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
例如输入“I am a student.”,则输出“student. a am I”。

*/ 
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std; 

void reverse(char *str,int len)
{
	char *p=str+len-1,ch;
	while(str<p)
	{
		ch=*str;
		*str=*p;
		*p=ch;
		str++;p--;
	} 
}

char* reverWord(char *s)
{
	int len=strlen(s);
	char *sen=s;
	reverse(sen,len);//整个翻转
	
	char *p=sen,*str;
	while (*p!='\0')
	{
		while(*p==' '&&*p!='\0') p++;
		str=p;//起始位置
		while(*p!=' '&&*p!='\0') p++;
		reverse(str,p-str); 
	}
	return sen;
}


int main(){
	
	char str1[]={"I am a student."};
	printf("%s ",str1);
	printf("翻转后:%s\n",reverWord(str1));
	
	char str2[]={"Hdfd are pig dog gg!"};
	printf("%s ",str2);
	printf("翻转后:%s\n",reverWord(str2));
	return 0;
}

抱歉!评论已关闭.