反转句子的单词顺序

输入一句英文,单词用空格隔开,要求在主函数里调用函数reverse()将这句话的单词从后向前翻转过来。
要求:必须使用函数
void reverse(char A[])
{

}

思路:可以先反转整个句子,再反转每个单词,也可以先反转每个单词再反转整个句子。

先反转每个单词:

#include<iostream>
using namespace std;
void Reverseword(char s[], int begin, int end)
{
while (begin < end)
{
char t = s[begin];
s[begin++] = s[end];
s[end--] = t;
}
}
void ReverseSte(char s[])
{
int e=0;
int k=0;
int length =strlen(s);
Reverseword(s, 0, length-1);
for (int i = 0; i < length; i++)
{
e = i;
if (s[e] == ' ')
{
Reverseword(s, k, e-1);
k = e + 1;
}
}
}


int _tmain(int argc, _TCHAR* argv[])
{
char arr[] =  "I am a student." ;
ReverseSte(arr);
cout << arr;
return 0;
}




#include<stdio.h>
#include<string.h>
void reverse_All(char *begin, char *end)
{
char temp;
while (begin<end)
{
temp = *begin;
*begin = *end;
*end = temp;
begin++;
end--;
}
}


void reverse(char *pstring)


{


int len = strlen(pstring);
char *pword_begin;
char *pword_end;
reverse_All(pstring, pstring + len - 1);//swap the whole string
pword_begin = pstring;
pword_end = pstring;
while(*pword_begin != '\0')
{
if (*pword_begin == ' ')
{
pword_begin++;
pword_end++;
}
else if (*pword_end == ' ' || *pword_end == '\0')
{
reverse_All(pword_begin, --pword_end);
pword_begin = ++pword_end;
}
else
{
pword_end++;
}
}
}
int main()
{
printf("Please input the string:\n");
char string[30] = "";
gets(string);
printf("After the reverse\n");
reverse(string);
puts(string);
return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值