Rotate a string in c++?

前端 未结 9 617
梦毁少年i
梦毁少年i 2020-12-29 00:57

I\'m looking for a way to rotate a string in c++. I spend all of my time in python, so my c++ is very rusty.

Here is what I want it to do: if I have a strin

9条回答
  •  一个人的身影
    2020-12-29 01:37

    There is a standard rotate function found in the algorithm header.
    If you want to do this yourself, you could try the following:

    #include 
    #include 
    
    std::string rotate_string( std::string s ) {
        if (s.empty()) return s;
    
        char first = s[0];
    
        s.assign(s, 1, s.size() - 1);
        s.append(1, first);
    
        return s;
    }
    
    int main() {
        std::string foo("abcde");
    
        std::cout << foo << "\t" << rotate_string(foo) <<  std::endl;
    
        return 0;
    }
    

    But of course, using the standard library is preferable here, and in most cases.

    EDIT #1 I just saw litb's answer. Beat again!
    EDIT #2 I just want to mention that the rotate_string function fails on strings of 0 length. You will get a std::out_of_range error. You can remedy this with a simple try/catch block, or use std::rotate :-)
    EDIT #3 Return the same string if the length of the string is 0.

提交回复
热议问题