cstringperformancealgorithmcstring

how to perform reversing a sentence Word by Word in 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);
  }
}

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

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


Solution

  • Perhaps this belongs on the code review site instead?

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

    should be

    wordend = strlen(words)-1;
    

    and

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

    should be

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

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