我正在练习一些编程问题,并尝试编写流行的“字符串中的反向单词”问题。
我试图用 C 编写我自己的代码。我能够部分正确。也就是说,“hello world”变成了“world olleh”。我想知道这里的错误是什么。我想在某个地方我正在创建一个 1 错误。
尽可能地,我想在不使用库函数的情况下做到这一点。我在这里搜索了这个问题并找到了很多解决方案,但我想知道为什么我的解决方案不起作用。
这是代码:
#include <stdio.h>
#include <string.h>
void reverse(char*, int);
int main(int argc, char **argv)
{
char st[]= "hello world";
int len = strlen(st);
int i=0,j=0;
reverse(st,len-1); // Reverse the entire string. hello world => dlrow olleh
while(st[j]){ //Loop till end of the string
if ( *(st+j) == ' ' || *(st+j) == '\0' ) { //if you hit a blank space or the end of the string
reverse(st+i,j-1); // reverse the string starting at position i till position before the blank space i.e j-1
i=++j; //new i & j are 1 position to the right of old j
}
else {
j++; //if a chacacter is found, move to next position
}
}
printf("%s",st);
return 0;
}
void reverse(char *s, int n)
{
char *end = s+n; //end is a pointer to an address which is n addresses from the starting address
char tmp;
while (end>s) //perform swap
{
tmp = *end;
*end = *s;
*s = tmp;
end--;
s++;
}
}
谢谢!
更新:根据@Daniel Fischer 的回答,这里是正确的实现:http: //ideone.com/TYw1k