#include "stdafx.h"
#include <iostream>
#include <stdio.h>
using namespace std;
#define MAX_LEN 256
//字符串循环右移动n位,如abcdefghi循环右移2位为hiabcdefg
//3种方法
void LoopMove(char *pStr, int steps)
{
char *ptem = pStr;
int len = 0;
while(*ptem != '\0')
{
ptem++;
len++;
}
if (steps%len == 0)
{
}
else
{
int needmove = steps%len;
for (int i=0; i<len-needmove; i++)
{
ptem[needmove+i] = pStr[i];
}
for (i=len-needmove; i<len; i++)
{
ptem[i-(len-needmove)] = pStr[i];
}
}
// pStr = &ptem;
for (int j=0; j<len; j++)
{
pStr[j] = ptem[j];
}
pStr[j] = '\0';
}
void LoopMove(char *pStr, int steps)
{
int needmove = steps%strlen(pStr);
int pos = strlen(pStr)-needmove;//尾部待移动的起始位置
char temp[MAX_LEN];
memset(temp, 0, MAX_LEN*sizeof(char));
strcpy(temp, pStr+pos);
strcpy(temp+needmove, pStr);
temp[strlen(pStr)] = '\0';
strcpy(pStr, temp);
}
void LoopMove(char *pStr, int steps)
{
int needmove = steps%strlen(pStr);
int pos = strlen(pStr) - needmove;
char temp[MAX_LEN];
memset(temp, 0, MAX_LEN*sizeof(char));
memcpy(temp, pStr+pos, needmove);
memcpy(temp+needmove, pStr, strlen(pStr)-needmove);
memcpy(pStr, temp, strlen(pStr));
}
int main()
{
char str[] = "abcdefghi";
int steps = 11;
cout << "Before" << endl;
cout << str << endl;
LoopMove(str, steps);
cout << "After" << endl;
cout << str << endl;
}
字符串循环右移动n位
最新推荐文章于 2022-11-17 10:12:50 发布