Reversing a string word by word in C++, C

There may be other way to doing that but I used the simple approach to do the same.
It is a two step process :

Step 1: Reverse the whole string.
Step 2: Reverse the words in the string.

Here is the code :

#include <iostream>
#include <conio.h>
#include <string>

using namespace std;

void reverse_string(char *str, char *end)
{
  for (char c; --end - str > 0; ++str)
  {
    c = *str;
    *str = *end;
    *end = c;
  }
}

void reverse_indiviualWords(char *str)
{
  char *end = str + strlen(str);

  reverse_string(str, end);

  while (end - str > 0)
  {
    char *token = str;

    while (*token != ' ' && *token)
    {
      ++token;
    }

    reverse_string(str, token);

    ++token; //For skipping spaces
    str = token;
  }
}

void main()
{
  char str[] = "How to reverse a string";
  
  cout << "Before :" << str << endl;
  reverse_indiviualWords(str);
  cout << "After :" << str << endl;

  _getch();
}

Thanks for visiting.
If you have any suggestions please leave a comment below

Comments

Popular Posts