欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

反转一个长字符串中的子字符串

程序员文章站 2022-05-20 17:49:58
...

第一次练习写博客,记录下自己感觉满意的成果吧

#include<stdio.h>
#include<string.h>

bool findPosition(char* sur, char *dst, int& start);
void reverseString(char* sur, int start, int len);

int main()
{
    char pStrSur[] = "weuyi qwei 09wer ()hellowneiqewr";
    char pStrDst[] = "hello";
    int iStart = 0;
    bool bIfHasSame = false;

    bIfHasSame = findPosition(pStrSur, pStrDst, iStart);
    if (bIfHasSame)
    {
        printf("the position is %d\n", iStart);
    }

    reverseString(pStrSur, iStart, strlen(pStrDst));
    printf("%s\n", pStrSur);
    reverseString(pStrSur, 0, strlen(pStrSur));

    printf("%s\n", pStrSur);
    return 0;
}

bool findPosition(char* sur, char *dst, int& start)
{
    char* pSur = sur;
    char* pDst = dst;

    for (int i=0; *pSur!='\0'; i++)
    {
        pSur = sur+i;
        if (*pSur == *pDst)
        {
            if (0 == start)
           {
                start = i;
            }

            pDst++;
            if (*pDst == '\0')
            {
                return true;
            }
        }
        else
        {
            if (0 != start)
            {
                start = 0;
                pDst = dst;
            }
        }
    }

    return false;
}

void reverseString(char* sur, int start, int len)
{
    char cTmp;
    for (int i=0; i<len/2; i++)
    {
        cTmp = *(sur+i+start);
        *(sur+i+start) = *(sur+start+len-i-1);
        *(sur+start+len-i-1) = cTmp;
    }
}

 

相关标签: 算法练习