## Tuesday, June 19, 2012

### string reverse in c

String reverse function is the one of the most common question you may face in C interviews. I will explain here, the concept and how to write the function to reverse the string and C code for that. In C we can do this in three ways like using arrays, pointers and recursion.

Using pointers and arrays: the concept is same for the both methods. But implementation is different. We can do the string reverse by maintaining two indices one from the begin and another one is from end. Swap the begin element and end  element, then increment begin index and decrement end index and again swap both the elements. And proceed this until begin  reaches half of the string. Because after that its already swapped.

Algorithm for string reverse function:
1. Get the string which is to be reversed
2. find the length of the string.
3. make two indices or pointers, one is pointing to beginning of the string and another one is pointing to end of the string (make end of the string one less than string length, because index starts from zero).
4. swap begin and end elements
5. increment begin and decrement end.
6. repeat from step 4 until begin reaches length/2.
C code for String reverse function using Arrays:
```void str_rev_arry(char *str)
{
int len = strlen(str);
int i=0,j=len-1;
for(i=0;i&lt;len/2;i++,j--)
{
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
```
C code for String reverse function using pointers:
```void str_rev_ptr(char *str)
{
int len = strlen(str);
int i;
char *begin, *end;
begin = str;
end = str+len-1;
for(i=0;i&lt;len/2;i++)
{
char temp = *begin;
*begin = *end;;
*end = temp;
begin++;
end--;
}
}
```

String reverse function using recursion: The recursion is calling same function itself repeatedly until it reaches some termination condition. so the concept is swapping the begin and end  elements repeatedly until begin reaches or greater than or equal to end. For every time we need to pass begin and end indices to the function along with string by increasing begin and decreasing end.

C code for String reverse function using recursion:
```void str_rev_rec(char *str, int begin, int end)
{
char temp;
if(begin>=end)
return;
temp = *(str+begin);
*(str+begin) = *(str+end);
*(str+end) = temp;
str_rev_rec(str, ++begin, --end);
}
```

String reverse program in C: Click Here for a complete working example with all three methods for string reverse function in C Programming language.