版权声明:本文为博主原创文章。未经博主同意不得转载。 https://blog.csdn.net/u012515223/article/details/37689725
左旋转字符串 代码(C)
本文地址: http://blog.csdn.net/caroline_wendy
题目: 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部.
请定义一个函数实现字符串左旋转操作的功能.
编程珠玑, 首先翻转前部分, 再翻转后部分, 最后所有翻转.
代码:
/*
* main.cpp
*
* Created on: 2014.6.12
* Author: Spike
*/
/*eclipse cdt, gcc 4.8.1*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Reverse(char* pBegin, char* pEnd) {
if (pBegin == NULL || pEnd == NULL)
return;
while (pBegin < pEnd) {
char temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
++pBegin, --pEnd;
}
}
char* LeftRotateString(char* pStr, int n) {
if (pStr == NULL)
return pStr;
int nLength = strlen(pStr);
if (nLength >0 && n>0 && n<nLength) {
char* pFirstStart = pStr;
char* pFirstEnd = pStr+n-1;
char* pSecondStart = pStr+n;
char* pSecondEnd = pStr+nLength-1;
Reverse(pFirstStart, pFirstEnd);
Reverse(pSecondStart, pSecondEnd);
Reverse(pFirstStart, pSecondEnd);
}
return pStr;
}
int main(void)
{
char pData[] = "abcdefg";
char* result = LeftRotateString(pData, 2);
printf("result = %s
", result);
return 0;
}
输出:
result = cdefgab