efficient approach to reverse a std::string object

Discussion in 'C++' started by July, Jul 16, 2005.

  1. July

    July Guest

    Hello all

    Recentlly, I was asked to write a program in which there is a function
    that need to reverse a std::string object.
    I wrote like this:
    string ReverseString(const string& srcStr)
    {
    string str;
    for(size_t i = 0; i < srcStr.length(); ++i)
    str += srcStr[srcStr.length() - i - 1];

    return str;
    }

    Is there any potential error in the ReverseString function?
    And if there is any more efficient approach to do this?
     
    July, Jul 16, 2005
    #1
    1. Advertising

  2. July

    benben Guest

    "July" <> wrote in message
    news:...
    > Hello all
    >
    > Recentlly, I was asked to write a program in which there is a function
    > that need to reverse a std::string object.
    > I wrote like this:
    > string ReverseString(const string& srcStr)
    > {
    > string str;
    > for(size_t i = 0; i < srcStr.length(); ++i)
    > str += srcStr[srcStr.length() - i - 1];
    >
    > return str;
    > }
    >
    > Is there any potential error in the ReverseString function?


    That you can debug...

    > And if there is any more efficient approach to do this?
    >


    std::reverse does exactly that.
     
    benben, Jul 16, 2005
    #2
    1. Advertising

  3. July

    msalters Guest

    July schreef:
    > Hello all
    >
    > Recentlly, I was asked to write a program in which there is a function
    > that need to reverse a std::string object.
    > I wrote like this:
    > string ReverseString(const string& srcStr)
    > {
    > string str;
    > for(size_t i = 0; i < srcStr.length(); ++i)
    > str += srcStr[srcStr.length() - i - 1];
    >
    > return str;
    > }
    >
    > Is there any potential error in the ReverseString function?

    Seems Ok.

    > And if there is any more efficient approach to do this?


    Reverse iterators:

    string ReverseString(const string& srcStr) {
    return string( srcStr.rbegin(), srcStr.rend() );
    }

    You might not even need the function, if you see how simple it
    really is.

    HTH,
    Michiel Salters.
     
    msalters, Jul 18, 2005
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. dogbite
    Replies:
    4
    Views:
    694
    osmium
    Oct 10, 2003
  2. Peter Jansson
    Replies:
    5
    Views:
    6,315
    Ivan Vecerina
    Mar 17, 2005
  3. Fei Liu
    Replies:
    9
    Views:
    447
  4. Jeffrey Walton
    Replies:
    10
    Views:
    942
    Mathias Gaunard
    Nov 26, 2006
  5. sanjib

    efficient approach to check a set bit

    sanjib, Dec 4, 2009, in forum: C Programming
    Replies:
    43
    Views:
    1,851
Loading...

Share This Page