Skip to main content

Reverse String Words Recursively C++


Problem Statment:Write a recursive function to reverse a string. Write a recursiveunction to reverse the words in a string, i.e., "cat is running" becomes "running is cat".
 

#include<iostream> 
 
 void reverse(char* begin, char* end){

  if(begin > end)
    return ;
  else{
    char temp = *begin;
    *begin = *end;
    *end = temp;
    reverse(begin+1,end-1);
  }
}

void reverse_word(char* start, char* begin ,char* end){

  if(*end=='\0'){ 
    reverse(begin,end-1);
    begin = end+1;
    reverse(start,end-1);  //reverse after all words are reversed
    return ;
   }
  
  if(*end==' '){  
    reverse(begin,end-1);
    begin =end+1;
  }
    reverse_word(start,begin,end+1);
}

int main( void ){

  char s1[] ="cat is running";  
 
  reverse_word(s1,s1,s1); 

  std::cout<<s1<<"\n";  // running is cat
  
  return 0;

}

Comments