Recursive and Iterative functions to reverse a string
Iterative functon
Not very difficult.
You need to just swap first character with last character, second with last but one, third with last but second and so on.
We can use a for loop to swap ith character with jth character. i starts with 0 and j with string length. And repeat the loop. Do not loop len times. Because we are swapping len/2 times.
Better still, continue the loop as long as i is less than j.
int len = strlen(str);
for(i=0,j=len-1;i<j;i++,j--)
{
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
That completes your operation. Not very difficult. Isn't it?
Note that we initialized j to len-1 because str[len] is null character ('\0')
Let us write complete function
void reverse(char *str)
{
int len = strlen(str);
int i,j;
for(i=0,j=len-1;i<j;i++,j--)
{
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
Recursive function to reverse a string
The problem here is you have so many function calls and you can not actually swap first character with last character and so on, as it is impossible to keep track of which character we are currently processing.
May be an easier way is to have another char array to which we copy the string in reverse. But again, since there are multiple function calls, each will have its own array and we do not get required result. What we need is a single array.
Also we need to copy the character to jth position of array. Again this j should be incremented for each recursive call.
Hence both j - an integer variable and a character array need to be static.
Once we have static array, we keep extracting one character at a time.
The steps are like this
- Extract one character - ch
- Reverse the rest of the string recursively
- Copy the char ch to jth location of static array
- Increment j
Let us write the function
char* reverse(char str[])
{
static int j=0;
static char arr[90];
char ch = *str;
if(ch!=0)
{
reverse(str+1);
arr[j++]=ch;
return arr;
}
}
Comments
Post a Comment