关于#c++#的问题:将字符串循环右移n个字符,例如abcde循环右移两位

定义函数,将字符串循环右移n个字符,例如abcde循环右移两位:deabc
函数接口定义:
void fun(char *str,int n)

img


img

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void fun(char *str,int n);
 
int main()
{
    char s[20];
    int n;
    scanf("%s%d",s,&n);
    fun(s, n);
    printf("%s", s);
    return 0;
}


void fun(char *str,int n)
{
    if ((str == NULL) || (n <= 0)) {
        return;
    } 
 
    int nLen = strlen(str);
    if (n >= nLen) {
        n = n % nLen;
    }
    
    char* pHead = (char*)malloc(n * sizeof(char));
    char* pTail = (char*)malloc((nLen - n) * sizeof(char));
    memset(pHead, 0 ,sizeof(pHead));
    memset(pTail, 0, sizeof(pTail));
    memcpy(pHead, str + nLen - n, n);
    memcpy(pTail, str, nLen - n);
 
    memcpy(str, pHead, n);
    memcpy(str + n , pTail, nLen - n);
    return;
}

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
void fun(char *str,int n)
{
    if ((str == NULL) || (n <= 0)) {
        return;
    } 
 
    int nLen = strlen(str);
    if (n >= nLen) {
        n = n % nLen;
    }
    
    char* pHead = (char*)malloc(n * sizeof(char));
    char* pTail = (char*)malloc((nLen - n) * sizeof(char));
    memset(pHead, 0 ,sizeof(pHead));
    memset(pTail, 0, sizeof(pTail));
    memcpy(pHead, str + nLen - n, n);
    memcpy(pTail, str, nLen - n);
 
    memcpy(str, pHead, n);
    memcpy(str + n , pTail, nLen - n);
    return;
}
 
int main()
{
    char s[20];
    int n;
    scanf("%s%d",s,&n);
    fun(s, n);
    printf("%s", s);
    return 0;
}
#include<bits/stdc++.h>
using namespace std;
string str;
int n;
deque<char> qu;//定义一个双向队列 
string fun(string str,int n){
    int len = str.length(); 
    //先把输入的字符串放队列 
    for(int i=0;i<len;i++){
        qu.push_back(str[i]);
    }
    
    //把队尾的元素插到队首 
    for(int i=0;i<n;i++) {
        char tail = qu.back();
        qu.pop_back();
        qu.push_front(tail);
    }
    
    deque<char>::iterator it = qu.begin();
    //遍历输出这个队列 
    for(it;it!=qu.end();it++){
        cout<<*it;
    }
}

int main() {
    cin>>str;
    cin>>n;
    fun(str,n);
    return 0;
}