微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在C语言中逐字执行句子?

如何解决如何在C语言中逐字执行句子?

也许这属于代码检查站点

您的方法对我来说似乎非常有效(除了我只调用一次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;   
    }

解决方法

#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

如果有人可以采用另一种方法来解决时间复杂性非常低的问题,或者如果它是正确的方法,那么我将不胜感激。谢谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。