我正在练习一些编程问题,并尝试编写流行的“字符串中的反向单词”问题。
我尝试用 C 编写自己的代码。我能够部分正确。也就是说,“hello world”变成了“world olleh”。我想知道这里的错误是什么。我想我在某个地方创建了一个 off by 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
最佳答案
问题是
while(st[j]){ //Loop till end of the string
if ( *(st+j) == ' ' || *(st+j) == '\0' )
while
条件防止在字符串末尾进入循环,因此最后一个单词不会再次反转。
你可以让它成为一个无限循环,然后添加一个
if (st[j] == '\0') break;
在反转之后,或者反转while循环离开后的最后一个单词。
关于c - 我的 C 代码中的错误,用于反转字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11278675/