Rotate a string in c++?

前端 未结 9 614
梦毁少年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:36

    Here's a solution that "floats" the first character to the end of the string, kind of like a single iteration of bubble sort.

    #include 
    
    string rotate(string s) {
      for (int i = 1; i < s.size(); i++)
        swap(s[i-1], s[i]);
      return s;
    }
    

    if you want the function to rotate the string in-place:

    #include 
    
    void rotate(string &s) {
      for (int i = 1; i < s.size(); i++)
        swap(s[i-1], s[i]);
    }
    

提交回复
热议问题