How to reverse a string in C, C++ without using library std::reverse function.

It is more like interview question then used in daily programming. There are multiple ways to do that and one of them is listed here :

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

using namespace std;

void reverse_string(char *str)
{
int len = strlen(str) - 1;
char temp;

for (int i = 0; i <= len / 2; ++i)
{
temp = str[i];
str[i] = str[len - i];
str[len - i] = temp;
}
}

void main()
{
char str[] = "How to reverse a string";

cout << "Before :" << str << endl;
reverse_string(str);
cout << "After :" << str << endl;
_getch();
}


Leave comments if you have any suggestions.
Thanks for visiting.

Comments

Popular Posts