2016-11-06 53 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; 
}