如何执行在C中扭转了一句话一个字一个字? [英] how to perform reversing a sentence Word by Word in C?

查看:131
本文介绍了如何执行在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是测试
我的预期成果是:
测试中是这样

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;   
    }

这篇关于如何执行在C中扭转了一句话一个字一个字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆