本文地址: 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\n", result); return 0; }
result = cdefgab
编程算法 - 左旋转字符串 代码(C),布布扣,bubuko.com
原文:http://blog.csdn.net/caroline_wendy/article/details/37689725