0

i have this reverse word function. it simply adding word to new string in reverse order . the problem with this code is it not print the last word ( first word before reverse ) . i dont know why . please help fix my code

    char str[100], revstr[100];
    int i, j, index, len, startIndex, endIndex;
    printf("\n Please Enter any String :  ");
    gets(str);

    len = strlen(str);
    index = 0;
    endIndex = len - 1;

    printf("\n *****  Given String in Reverse Order  ***** \n");        
    for(i = len - 1; i > 0; i--)
    {
        if(str[i] == ' ')
        {
            startIndex = i + 1;

            for(j = startIndex; j <= endIndex; j++)
            {
                revstr[index] = str[j];
                index++;
            }
            revstr[index++] = ' ';
            endIndex = i - 1;               
        } 
    }

    printf("\n Given String in Reverse Order = %s", revstr); 
    return 0;
phuonglinh
  • 23
  • 4
  • In the line `revstr[index++] = ' ';` you are overwriting something you should not be , but I can't quite see why. Although the whole code is pretty much bound to cause string overflow anyway, using `gets`. Please read [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Weather Vane May 03 '20 at 19:01
  • ... I added a line to print the value which you are about to overwrite and entered `one two three` and my output was `FE` then `4D` then a distorted string. Follow it through with a debugger. – Weather Vane May 03 '20 at 19:05

1 Answers1

0

Here's a working code:

    char str[100], revstr[100];
    int i, j, index, len, startIndex, endIndex;
    printf("\n Please Enter any String :  ");
    gets(str);
    len = strlen(str);
    index = 0;
    endIndex = len - 1;

    printf("\n *****  Given String in Reverse Order  ***** \n");        
    for(i = len - 1; i >= -1; i--)
    {
        if(i == -1){
            startIndex = i + 1;

            for(j = startIndex; j <= endIndex; j++)
            {
                revstr[index] = str[j];
                index++;
            }
            revstr[index++] = ' ';
            endIndex = i - 1;  
            break;
        }
        if(str[i] == ' ')
        {
            startIndex = i + 1;

            for(j = startIndex; j <= endIndex; j++)
            {
                revstr[index] = str[j];
                index++;
            }
            revstr[index++] = ' ';
            endIndex = i - 1;               
        } 
    }

    printf("\n Given String in Reverse Order = %s", revstr); 

The problem was that you were only including a word if there was a space before it. There will be no space before the first word therefore I made the code go before the first letter and always include the first word forcefully. This code can be broken if there are more spaces than needed in the text.

Mahmood Darwish
  • 536
  • 3
  • 12