弦旋转r个位置

string rotation by r places

本文关键字:位置 旋转      更新时间:2023-10-16

我试图用'r'位置旋转我的字符串,但面临一些问题。以下是我的代码(函数)。请帮助。例如:r=3之后的hello coding.应该变成ng.hello codi

void fnc(){
char a[100],key;
int n,r,i,t=1,total=0,count,x;
cin>>n;                           //no. of test cases
while(t<=n){
    cin>>r;                       //no. of rotations
    cin.get();
    cin.get(a,100);
     for(i=0; a[i]!= ''; i++){
        //cout<<a[i];
        total++;
    }
    cout<<total;
    for(i=0; i<r; i++){
        key = a[total-1];
        cout<<"key: "<<key<<endl;
        for(i=total-2; i>=0; i--){
            a[i+1] = a[i];
        }
        a[0] = key;
    }
    for(i=0; a[i]!= ''; i++){
        cout<<a[i];
    }
    ///cout<<a<<endl;
    t++;
}

}

这里有一种只使用迭代器的方法:

#include <string>
#include <iostream>
using namespace std;
int mod(int a, unsigned int b) {
  int ret = a % b;
  return ret>=0 ? ret : b + ret;
}
string rotate(const string sentence, int rotation) {
  rotation = mod(rotation, sentence.size());
  string rotatedSentence;
  for(auto itr=sentence.begin(); itr < sentence.end(); ++itr) {
    if (distance(sentence.begin(), itr) < rotation) {
      rotatedSentence.push_back(*(itr + sentence.size() - rotation));
    } else {
       rotatedSentence.push_back(*(itr - rotation));
    }
  }
  return rotatedSentence;
}
int main() {
  const string sentence = "hello coding.";
  cout << sentence << endl;
  cout << rotate(sentence, 3) << endl; //prints ng.hello codi
  return 0;
}