1.String reverse order all string.
#include <stdio.h>
#include <string.h>
/*
*"abcdefg"->"gfedcba"
*/
void reverse(char *p, char *q)
{
char tmp = 0;
while(p<q){ /*exchange*/
tmp = *q;
*q = *p;
*p = tmp;
p++;
q--;
}
return;
}
int main()
{
char str[100] = {0};
char *p = str;/*head*/
char *q = NULL;
scanf("%s", str);
q = &str[strlen(str)-1];/*tail*/
reverse(p, q);/*head and tail exchange*/
printf("%s\n", str);
return 0;
}
2.String reverse order as word.
#include <stdio.h>
#include <string.h>
/*
*"hua wei niu bi"->"auh iew uin ib"->"bi niu wei hua"
*/
void reverse(char *p, char *q)
{
char tmp = 0;
while(p<q){
tmp = *q;
*q = *p;
*p = tmp;
p++;
q--;
}
return;
}
int main()
{
char str[100] = {0};
char *p = str;/*word head*/
char *q = str;/*space*/
fgets(str, 100, stdin);
str[strlen(str)-1] = 0;/*lastest is '\n'*/
while(*q != '\0'){
if (*q == ' '){
reverse(p, q-1);
q++;
p = q;
}else{
q++;
}
}
reverse(p, q-1);/*lastest word*/
reverse(str, q-1);/*all string*/
printf("%s\n", str);
return 0;
}