string reversal

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jerico
    New Member
    • Sep 2006
    • 39

    string reversal

    Hi.How can a string be reversed without using a loop?thanks for any help.

    Jerico
  • arne
    Recognized Expert Contributor
    • Oct 2006
    • 315

    #2
    Originally posted by jerico
    Hi.How can a string be reversed without using a loop?thanks for any help.

    Jerico
    You mean something like

    string string_reverse( const string& s ) {
    string ret;
    copy( s.rbegin(), s.rend(), back_inserter( ret ) );
    return ret;
    }

    Comment

    • zahidkhan
      New Member
      • Sep 2006
      • 22

      #3
      Originally posted by arne
      You mean something like

      string string_reverse( const string& s ) {
      string ret;
      copy( s.rbegin(), s.rend(), back_inserter( ret ) );
      return ret;
      }

      If you want to avoid for loop or while loop then you have to use recursion

      void str_reverse(cha r str[],int startIndex,int endIndex)
      {
      if(startIndex >= endIndex) return;
      str_reverse(str ,++startIndex,--endIndex);
      str[startIndex-1]^=str[endIndex]^=str[startIndex-1]^=str[endIndex];
      }
      int main(int argc,char* argv[])
      {
      char str[] = "MyString";
      str_reverse(str ,0,strlen(str)) ;
      printf("%s\n",s tr);
      return 0;
      }

      Comment

      • D_C
        Contributor
        • Jun 2006
        • 293

        #4
        Just a hint, any tail end recursion can be converted into a while loop, and that's precisely what most (all?) compilers do.

        Comment

        Working...