[C++]学习字符串Str左移m位的解决方案
测试代码
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
using std::cin;
using std::cout;
using std::string;
using std::endl;
//做一次从from到to的字符交换
void ReverseString(string &str,int from,int to) {
while (from < to) {
char c = str.at(from);
str.at(from) = str.at(to);
str.at(to) = c;
from++;
to--;
}
}
//字符串str左移m位
void LeftRotationStr(string &str, int m) {
int n = str.length();
m %= n;
ReverseString(str,0, m - 1);
ReverseString(str, m, n - 1);
ReverseString(str, 0, n - 1);
}
int main()
{
string str = "hijklmn";
for (int i = 1; i <= str.length(); i++) {
cout << "移动: " << i << endl;
cout << "before: "<< str << endl;
//ReverseString(str, 1, 3);
LeftRotationStr(str, i);
cout << "after: " << str << endl << endl;
}
system("pause");
return 0;
}
测试结果
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。