1.倒叙整个字符串
#include <stdio.h>
#include <assert.h>#include <string.h>
char *Reverse(char *str)
{
assert(str!=NULL);
char *start_str = str;
char tmp;
int len = strlen(str);
int i = 0;
while (start_str<&str[len-i-1])
{
tmp = *start_str;
*start_str = str[len-i-1];
str[len-i-1] = tmp;
start_str++;
i++;
}
}
int main(void)
{
char src_str[] = "hello world";
Reverse(src_str);
printf("%s\n", src_str);
}
或者
#include <stdio.h>
#include <assert.h>
#include <string.h>
char *Reverse(char *str)
{
assert(str!=NULL);
char *start_str = str;
char *end_str = str;
char tmp;
while (*end_str)
{
end_str++;
}
while (start_str<--end_str)
{
tmp = *start_str;
*start_str = *end_str;
*end_str = tmp;
start_str++;
}
return str;
}
int main(void)
{
char src_str[] = "hello world";
Reverse(src_str);
printf("%s\n", src_str);//dlrow olleh
}
2. 以空格为界将hello world变成olleh dlrow
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 20
void change(char *str1, char *str2)
{
char tmp;
while (str1 < str2)
{
tmp = *str1;
*str1 = *str2;
*str2= tmp;
str1++;
str2--;
}
}
void reverse(char *str_src)
{
char *start = str_src;
char *end = str_src;
while (*start)
{
if (*start == ' ')
{
start++;
end++;
}
else if (*end == ' '||*end == '\0')
{
change(start, --end);
start = ++end;
}
else
{
end++;
}
}
}
int main(void)
{
char *str = (char*)malloc(N*sizeof(char));
gets(str);
printf("the string before inverse\n");
puts(str);
reverse(str);
printf("the string after inverse\n");
puts(str);
free(str);
}