How To make a function that reverses a string

Well i was just wondering how to create a string reverse function as there is a include file 'string.h' which contains the strrev function.Just for knowledge sake i want to know how actually string gets reversed. Any ideas?
You can run a counter 'i' from first character to half the length of the string. Just keep swapping the values of S[i] & S[ L- i - 1 ], where L is length of string.

O(N) time complexity and O(1) space complexity.
Last edited on
This should let you get started :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
char * stringrev2(char *str)
{
   int i, len;
   char temp;

   len = strlen(str);

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


1
2
3
4
5
6
int main()
{
   std::cout << "abcdef becomes " << stringrev2("abcdef") << std::endl;
   system("pause");
   return 0;
}
Ohk ... i actually tried to reverse a string like storing the last character of the string in the first array for that string...

And then so on..
Last edited on
Topic archived. No new replies allowed.