您的位置:首页 > 职场人生

一道面试题

2013-11-04 12:12 232 查看
反转句子的单词顺序!

for example:

this is a apple 

to :

apple a is this

#include "stdafx.h"
#include<stdio.h>

//将单个单词的字母顺序反转
void ReverseWords(char* x,char* y)
{
char t = *x;
while(x < y)
{
t = *x;
*x = *y;
x++;
*y = t;
y--;
}
}

char* ReverseSentence(char* Sentence)
{
char* p = Sentence; // p 指向句子的首个字母
char* q = p;	    // q 指向句子的空格或'\0'
while (*q != '\0')
{
if (*q == ' ')  // p 指向句子首个字母 q 指向单词的最后一个字母
{
// 比如:p -> this is a apple
//	 q-1 -> s is a apple
ReverseWords(p,q-1);
// 结果:p -> siht is a apple
q++;
p = q;
}
else
q++;
}
ReverseWords(p,q-1);         // 反转最后一个单词
ReverseWords(Sentence,q-1);  // 反转整个句子
return Sentence;
}

void main()
{
char Sentence[] = "this is a apple";
char* Res = ReverseSentence(Sentence);
printf("%s",Res);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: