试题 5:编写一个函数,作用是把一个 char 组成的字符串循环右移 n 个。比如原来是"abcdefghi"
如果 n=2,移位后应该是"hiabcdefgh"
我的方法:
void loopMove(char* const& pChar, int steps)
{
unsigned int len=strlen(pChar);
if (steps>len)
{
steps=steps%len;
}
else if(steps==len)
{
return;
}
int times=len/steps; //整块的交换 的次数
int remains=len%steps; //残块的个数
char* pStart=pChar;
while (--times>0)
{
pStart+=steps;
for (int tmp=0;tmp {
pChar[tmp]+=pStart[tmp];
pStart[tmp]=pChar[tmp]-pStart[tmp];
pChar[tmp]=pChar[tmp]-pStart[tmp];
}
}
//临界情况的处理
bool flag=false;
pStart+=steps;
for (int tmp=0;tmp {
if (pStart[tmp]=='\0'||(flag==true))
{
pChar[tmp]+=pChar[tmp-remains];
pChar[tmp-remains]=pChar[tmp]-pChar[tmp-remains];
pChar[tmp]=pChar[tmp]-pChar[tmp-remains];
flag=true;
}
else{
pChar[tmp]+=pStart[tmp];
pStart[tmp]=pChar[tmp]-pStart[tmp];
pChar[tmp]=pChar[tmp]-pStart[tmp];
}
}
}
void main(void)
{
char str1[]="abcdefghi";
cout< loopMove(str1,4);
cout<}
-------------------------参考方法-----------------
正确解答1:
void LoopMove ( char *pStr, int steps )
{
int n = strlen( pStr ) - steps;
char tmp[MAX_LEN];
strcpy ( tmp, pStr + n );
strcpy ( tmp + steps, pStr);
*( tmp + strlen ( pStr ) ) = '\0';
strcpy( pStr, tmp );
}
正确解答 2:
void LoopMove ( char *pStr, int steps )
{
int n = strlen( pStr ) - steps;
char tmp[MAX_LEN];
memcpy( tmp, pStr + n, steps );
memcpy(pStr + steps, pStr, n );
memcpy(pStr, tmp, steps );
}
----------------------字符串逆序--------------------
// 遍历。如果字符大于0x80,则为中文,将连续的两个字符一起放到新字符串的末尾
// from :
// 1 看main函数中 形式,最后在 子函数的外面delete
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
char * Inverse(const char * pSrc)
{
int len = strlen(pSrc);
if ( len ) {
char * pTarget = new char[len];
unsigned char * p1 = (unsigned char *)pSrc;
char * p2 = pTarget + len - 1;
for ( int i=0; i {
if ( *p1 <=0x80 )
*p2-- = *p1++;
else {
*p2 -- = p1[1];
*p2 -- = *p1;
p1 += 2;
i++;
}
}
return pTarget;
} else
return NULL;
};
int main()
{
char * pSrc = "This 是一个 C++程序";
char * pT = Inverse(pSrc);
printf("%s", pT);
delete pT;
return 0;
};
阅读(1751) | 评论(0) | 转发(0) |