字符串循环左移:

给定一个字符串,要求把S的前k个字符移动到S的尾部,如把字符串"abcdef"前面的2个字符'a','b'移动到字符串的尾部,得到新字符"cdefab",即字符串循环左移k位。

程序实现:

 1 /***************************************
 2 FileName ReverseString.cpp
 3 Author : godfrey
 4 CreatedTime : 2016/5/1
 5 ****************************************/
 6 #include <iostream>
 7 #include <cstring>
 8 #include <stdio.h>
 9 #include <stdlib.h>
10 
11 using namespace std;
12 
13 void ReverseString(char* str,int from,int to){
14     char t;
15     while(from < to){
16         t = str[from];
17         str[from++] = str[to];
18         str[to--] = t;
19     }
20 }
21 
22 void LeftRotateString(char* str,int n,int m){
23     m %= n;
24     ReverseString(str,0,m-1);
25     ReverseString(str,m,n-1);
26     ReverseString(str,0,n-1);
27 }
28 int main()
29 {
30     char str[] = "abcdef";
31     cout<<str<<endl;
32     LeftRotateString(str,strlen(str),2);
33     cout<<"-------------LeftRotate 2----------"<<endl;
34     cout<<str<<endl;
35     return 0;
36 }

运行结果:

转载请注明出处:

C++博客园:godfrey_88

http://www.cnblogs.com/gaobaoru-articles/