如何在C语言中逐字执行句子?
#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
如果有人可以采用另一种方法来解决时间复杂性非常低的问题,或者如果它是正确的方法,那么我将不胜感激。谢谢
回答:
也许这属于代码检查站点?
您的方法对我来说似乎非常有效(除了我只调用一次strlen(words)并将结果保存在寄存器中)。
两个可能的错误如下所示:
wordend = strlen(words);
应该
wordend = strlen(words)-1;
和
for(j = wordstart ; j <= (wordend - wordstart) / 2 ; ++j) {
应该
for(j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
最终代码看起来像(带有一些额外的{}):
#include <stdio.h> int main(int argc,char *argv[])
{
int i,j;
char words[]= "this is a test";
int L=strlen(words);
// Reverse each word
for(i = 0; i < L; ++i) {
int wordstart = -1;
int wordend = -1;
if(words[i] != ' ')
{
wordstart = i;
for(j = wordstart; j < L; ++j) {
if(words[j] == ' ') {
wordend = j - 1;
break;
}
}
if(wordend == -1)
wordend = L-1;
for(j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
char temp = words[j];
words[j] = words[wordend - (j - wordstart)];
words[wordend - (j - wordstart)] = temp;
}
i = wordend;
}
}
printf("reversed string is %s:",words);
return 0;
}
以上是 如何在C语言中逐字执行句子? 的全部内容, 来源链接: utcz.com/qa/404653.html