c++ - string rotation by r places -


i'm trying rotate string 'r' places facing problem.the following code(function).please help. eg: hello coding. after r=3 should become 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]!= '\0'; 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]!= '\0'; i++){         cout<<a[i];     }      ///cout<<a<<endl;      t++; } 

}

here way of doing using iterators:

#include <string> #include <iostream>  using namespace std;  int mod(int a, unsigned int b) {   int ret = % 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; } 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -