【发布时间】:2012-03-26 16:54:00
【问题描述】:
#include <stdio.h>
int main(void)
{
int i,j;
int wordstart = -1;
int wordend = -1;
char words[]= "this is a test";
char temp;
// Reverse each word
for (i = 0; i < strlen(words); ++i)
{
wordstart = -1;
wordend = -1;
if(words[i] != ' ')
wordstart = i;
for (j = wordstart; j < strlen(words); ++j)
{
if(words[j] == ' ')
{
wordend = j - 1;
break;
}
}
if(wordend == -1)
wordend = strlen(words);
for (j = wordstart ; j <= (wordend - wordstart) / 2; ++j)
{
temp = words[j];
words[j] = words[wordend - (j - wordstart)];
words[wordend - (j - wordstart)] = temp;
}
i = wordend;
printf("reversed string is %s:", words);
}
}
我尝试过这种方式,但我得到了这个输出:siht is a test
我的预期输出是:test a is this
如果有人可以提出一种不同的方法,这种方法的时间复杂度非常低,或者如果它是正确的方法,我将不胜感激。谢谢
【问题讨论】:
-
@MichaelBurr 你能指出我犯的错误吗
标签: c string performance algorithm cstring