旋转字符串

   1:  /*
   2:  author:justinzhang
   3:  email:uestczhangchao@gmail.com
   4:  time:2012-8-19 9:44:46
   5:  des.: to left rotate a string,e.g, abcedef->cedefab
   6:  */
   7:   
   8:  #include <iostream>
   9:  #include <string>
  10:  using namespace std;
  11:   
  12:  void swap_str(string &str, int i, int j)
  13:  {
  14:      char c = str[i];
  15:      str[i] = str[j];
  16:      str[j] = c;
  17:  }
  18:   
  19:  /*
  20:      This routine is used to reverse a string,e.g,abcd->dcba
  21:  */
  22:  void reverse_str(string &str,int start, int end)
  23:  {
  24:      for(;start<end;start++,end--)
  25:      {
  26:          swap_str(str, start, end);
  27:      }
  28:  }
  29:   
  30:  /*
  31:      This routine is used to left_shift a string by offset  bits,e.g.
  32:      left shift string abcdefg by 2 bits, we get results:cdefgab;
  33:      we first devide the string by two parts,AB, first we reverse A, then we
  34:      reverse B, the we get string A'B',finally, we reverse A'B',That's the result we want;
  35:  */
  36:  string &left_rotate_string(string &str, int offset)
  37:  {
  38:      int len = str.length();
  39:      cout << len << endl;
  40:      reverse_str(str, 0, offset-1);
  41:      reverse_str(str, offset, len-1);
  42:      reverse_str(str, 0, len-1);
  43:      return str;
  44:  }
  45:   
  46:  /*
  47:      This routine is used to right_shift a string by offset  bits,e.g.
  48:      right shift string abcdefg by 2 bits, we get results:fgabcde
  49:  */
  50:  string &right_rotate_string(string &str, int offset)
  51:  {
  52:      int len = str.length();
  53:      reverse_str(str, 0, len-offset-1);
  54:      reverse_str(str, len-offset, len-1);
  55:      reverse_str(str, 0, len-1);
  56:      return str;
  57:  }
  58:   
  59:   
  60:  int main()
  61:  {
  62:      string str;
  63:      cin >> str;
  64:      str = left_rotate_string(str,2);
  65:      cout << str << endl;
  66:      str = right_rotate_string(str,2);
  67:      cout << str << endl;
  68:      return 0;
  69:  }
  70:   
  71:   
  72:   
  73:   
posted @ 2012-09-01 23:20  justinzhang  阅读(241)  评论(0编辑  收藏  举报