运行此代码.你可以将"长寿和繁荣"转变为"繁荣和万岁".
#include <stdio.h>
#include <string.h>
void rev(char *l, char *r);
int main(int argc, char *argv[])
{
char buf[] = "live long and prosper";
char *end, *x, *y;
// Reverse the whole sentence first..
for(end=buf; *end; end++);
rev(buf,end-1);
// Now swap each word within sentence...
x = buf-1;
y = buf;
while(x++ < end)
{
if(*x == '\0' || *x == ' ')
{
rev(y,x-1);
y = x+1;
}
}
// Now print the final string....
printf("%s\n",buf);
return(0);
}
// Function to reverse a string in place...
void rev(char *l,char *r)
{
char t;
while(l < r)
{
t = *l;
*l++ = *r;
*r-- = t;
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道,在C++中使用header,有什么好的快速方法可以做到这一点吗?谢谢!
您可能希望使用头文件中std::reverse提供的函数<algorithm>.