要求:必须使用函数
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;
}