[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;
}

測試結果

這裏寫圖片描述

發佈了167 篇原創文章 · 獲贊 25 · 訪問量 60萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章