如何执行在C中扭转了一句话一个字一个字?一个字、句话

由网友(深夜、独徘徊)分享简介:#include int main(void){int i,j;int wordstart = -1;int wordend = -1;char words[]= "this is a test";char temp;// Reverse each wordfor (i = 0; i < strle...
#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是测试 我的预期成果是: 测试中是这样

I tried in this way but i am getting this output: siht is a test my expected output is: test a is this

我会AP preciate如果有一个人能来用不同的方式为它的时间复杂度是非常少的,或纠正我,如果这是正确的做法。谢谢

I would appreciate if some one could come with a different approach for which time complexity is very less or correct me if it is the right approach. Thanks

推荐答案

也许,这属于在code评论网站呢?

Perhaps this belongs on the code review site instead?

您的做法似乎很有效,我(除了我只会调用strlen(字)一次,并将结果保存在一个寄存器)。

Your approach seems very efficient to me (except that I would only call strlen(words) once and save the result in a register).

有两种可能的错误是这样的:

Two possible bugs look like:

wordend = strlen(words);

wordend = strlen(words)-1;

for(j = wordstart ; j <= (wordend - wordstart) / 2 ; ++j) {

for(j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {

最后code样子(有一些额外的{}):

Final code looks like (with some extra {}):

    #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;   
    }
阅读全文

相关推荐

最新文章