程序员面试题100题第21题——左旋转字符串

题目:把字符串前n个字符移到字符串的尾部。

如:abcdef左旋转2位得到字符串cdefab;

分析得:左旋转其实为3个反转操作!

代码如下:(主要const的使用)

const在*左边修饰指针指向的内容,即内容不能修改

const在*右边修饰指针本身,即指针本身不能修改

即//左内容右本身

char* ReverseString(char * const pStart, char * const pEnd)//反转字符串
{//const不修改指针
  //左内容右本身
    char *pS=pStart;
    char *pE=pEnd;

    if(pS != NULL && pE != NULL)
    {
        char temp;
        while(pS <= pE)
        {
            temp=*pS;
            *pS=*pE;
            *pE=temp;
            pS++;
            pE--;
        }
    }
    return pStart;
}

 

char* ReverseLeftNumChar(char * const pStart, unsigned int n)
{//const 
    unsigned int iLen=strlen(pStart);

    if(n>0 && iLen>0 && iLen>n)
    {
        ReverseString(pStart,pStart+n-1);
        ReverseString(pStart+n,pStart+iLen-1);
        ReverseString(pStart,pStart+iLen-1);
    }
    return pStart;
}
posted @ 2012-10-01 21:31  logzh  阅读(261)  评论(0编辑  收藏  举报