function_1:
1、将第一个字符串移到末尾;
2、执行上面的步骤n次,就可以将前n个字符移到末尾
源码:
//将字符串的前n个字符移到末尾去 #include <iostream> using namespace std; //将第一个字符移动到末尾 void move_one_char_to_tail(char*str)//字符数组 { int len = strlen(str); char temp = str[0]; int i; for (i = 0; i < len - 1; i++) { str[i] = str[i + 1]; } str[i] = temp; } //将前n字符移到字符串末尾 //方法为将第一字符移到末尾,执行n次 void move_n_char_to_tail(char*str, int n) { int len = strlen(str); while (n-- != 0) { move_one_char_to_tail(str); } } int main() { char str[50] = { '\0' }; int n; cout << "输入一个字符串:" << endl; cin >> str; cout << "输入旋转字符串的个数:"; cin >> n; move_n_char_to_tail(str, n); cout << str; system("pause"); }
function_2:
方法:将前n个字符移到末尾,先将前n字符旋转,再将n后的字符旋转,最后旋转整个字符串
源码:
//将字符串的前n个字符移到末尾去
#include <iostream>
using namespace std;
//交换字符数组中start到end之间的字符
void swap_start_to_end(char*str,int from, int end)
{
while (from < end)
{
char temp = str[from];
str[from++] = str[end]; //首字符等于末字符,将首字符后移一位
str[end--] = temp;//末字符等于首字符,将末字符前移一位
//直到首尾字符相遇
}
}
//将前n个字符移到字符串尾部
//方法:先将前n个字符交换,再将n后的字符交换,最后将整个字符串交换
void move_n_char_to_tail(char*str, int n)
{
int len = strlen(str);
swap_start_to_end(str, 0, n - 1);
swap_start_to_end(str, n, len-1);
swap_start_to_end(str, 0, len-1);
}
int main()
{
char str[50] = { '\0' };
int n;
cout << "输入一个字符串:" << endl;
cin >> str;
cout << "输入旋转字符串的个数:";
cin >> n;
move_n_char_to_tail(str, n);
cout << str;
system("pause");
}