Another way of reversing individual words in a string in C++, C.
In the previous post I mentioned the one of the method to doing the same. Here I am providing the another method to doing the same.
Here is the code :
Thanks for visiting.
If you have any suggestions please leave a comment below.
#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);
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();
}
Links : Method OneThanks for visiting.
If you have any suggestions please leave a comment below.
Comments
Post a Comment