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");
}