Brian R. McCabe
Brian R. McCabe

Reputation: 37

Reverse each word in a string using C

Ok, so this code almost works, only it messes up the end of every line. For instance, if I have as my stdin a text file with these three lines:

This is a test
For you to see
How this code messes up

Output reads:

siht si a
tsetroF uoy ot
eeswoH siht edoc sessem
pu

Let me know if you catch anything Thanks

void reverse(char *beg, char *end)
{
  while (beg<end)
  {
    char temp = *beg;
    *beg++ = *end;
    *end-- = temp;
  }
}


void reverseWords(char *str)
{
  char *beg = NULL;
  char *temp = str;
  while (*temp)
  {
    if ((beg == NULL) && (*temp != ' '))
    {
      beg = temp;
    }
    if (beg && ((*(temp + 1) == ' ') || (*(temp + 1) == '\0')))
    {
      reverse(beg, temp);
      beg = NULL;
    }
  temp++;
  }
}

Upvotes: 1

Views: 887

Answers (1)

Bishoy
Bishoy

Reputation: 725

New lines in your code are not taken into consideration.

In the code below I've changed all the occurrences of *something == ' ' to a call to the newly added method isWhiteSpace, which returns true if the character being checked is either a space, a tab, a newline, or a carriage return character:

void reverse(char *beg, char *end)
{
  while (beg<end)
  {
    char temp = *beg;
    *beg++ = *end;
    *end-- = temp;
  }
}

int isWhiteSpace(char value)
{
  return value == ' ' || value == '\t' || value == '\r' || value == '\n';
}


void reverseWords(char *str)
{
  char *beg = NULL;
  char *temp = str;
  while (*temp)
  {
    if ((beg == NULL) && !isWhiteSpace(*temp))
    {
      beg = temp;
    }
    if (beg && (isWhiteSpace(*(temp + 1)) || (*(temp + 1) == '\0')))
    {
      reverse(beg, temp);
      beg = NULL;
    }
  temp++;
  }
}

Upvotes: 1

Related Questions