標籤:mystra 編程演算法 左旋轉字串 代碼 c
左旋轉字串 代碼(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\n", result);return 0;}
輸出:
result = cdefgab