方法一:字符串遍历移动
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
char temp;
int n;//向右移动n位
cin >> str;
cin >> n;
int len = str.size();
for(int i = 0; i < n; i++)//每一轮向右移动1位
{
temp = str[len-1];//暂存字符串最后一位即第len-1位的字符,这一轮后放到字符串头部
for(int k = len-2; k >= 0; k--)
str[k+1] = str[k];//从len-1位到第1位依次赋值(原字符串整体右移一位)
str[0] = temp;
}
cout << str << ' ';
system("pause");
return 0;
}
方法二:合并两个相同字符串后截取
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
string temp;
string res;
int n;//向右移动n位
cin >> str;
cin >> n;
int len = str.size();
temp = str + str; //两个相同字符串合并
res = temp.substr(len-n, len);//取出合并后字符串中第len-n位开始的len个字符
cout << res << ' ';
system("pause");
return 0;
}