zoukankan      html  css  js  c++  java
  • 编程算法

    版权声明:本文为博主原创文章。未经博主同意不得转载。 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
    







  • 相关阅读:
    第九篇 正则表达式
    第八篇、递归、装饰器
    第四篇、函数和递归
    第二篇、HTML
    nginx rewrite标签配置以及用户认证配置
    nginx location
    nginx日志配置,以及日志轮询
    nginx别名配置,状态配置,include优化
    第一篇 先用socket模拟web服务器
    第二十八篇、自定义线程池
  • 原文地址:https://www.cnblogs.com/mqxnongmin/p/10719473.html
Copyright © 2011-2022 走看看