2016-11-06 9 views
-1

文字列を 'r'個の場所で回転させようとしていますが、何らかの問題に直面しています。次のコードは機能です。 の場合:hello coding.r=3の後にはng.hello codiになるはずです。ここでr個の文字列の回転

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

}

+2

http://en.cppreference.com/w/cpp/algorithm/rotate実装を見てくださいあなたの好きなIDEで。 –

答えて

0

のみイテレータを使用してこれを行う方法です:

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