moc 发表于 2018-8-8 16:45:35

007-字符串的三种典型模型

本帖最后由 moc 于 2018-8-8 16:47 编辑

1、字符串的拷贝--推演
#include "stdlib.h"
#include "stdio.h"
#include "string.h"

void copy_str2(char *from, char *to)
{
        for (;*from != '\0';to++,from++)
        {
                *to = *from;
        }
        *to = '\0';
}

// 后缀++的优先级高于*p,所以先执行*p,在执行++,{后缀(先执行在++)}
void copy_str3(char *from, char *to)
{
        while (*from != '\0')
        {
                // *to = *from;
                // to++; from++;
                *to++ = *from++;
        }
        *to = '\0';
}

//上面函数继续优化
void copy_str4(char *from, char *to)
{
        while ((*to++ = *from++) != '\0') ;
}

void main()
{
        char from;
        charto;

        strcpy_s(from, "adadada123");
        copy_str4(from, to);
        printf("%s", to);

        system("pause");
}

2、两头堵模型
#include "stdlib.h"
#include "stdio.h"
#include "string.h"

//两头堵,去除两边的空格,得出中间字符串的长度
int trispace(char * inbuf, char *outbuf)
{
        int count = 0, ret = 0;
        int i = 0, j = 0;

        char *p = inbuf;
        j = strlen(p) - 1;

        //浮动指针查找关键位置
        while (p == ' ' && p != '\0')
        {
                i++;
        }

        while (p == ' ' && j > 0)
        {
                j--;
        }

        count = j - i + 1;
        printf("count:%d\n", count);

        memcpy(outbuf, inbuf + i, count);
        outbuf = '\0';

        return ret;
}

voidmain()
{
        int ret = 0;
        char bu = NULL;

        //char *p = "   abcdefg   ";
        char buf[] = "   abcdefg   ";
        char buf2;

        ret = trispace(buf, buf2);
        if (ret != 0)
        {
                printf("fun Error: code %d", ret);
        }
        printf("buf2:%s", buf2);

        system("pause");
}
3、字符串反转模型
#include "stdlib.h"
#include "stdio.h"
#include "string.h"

//求取已知字符串的反序
void main()
{
        char c;
        //char *str;
        char str[] = "abcdefg";
        int len = strlen(str);
        char *p1 = str;
        char *p2 = str + len - 1;

        //利用首尾指针取*不断交换
        while (p1 < p2)
        {
                c = *p1;
                *p1 = *p2;
                *p2 = c;
                p1++;
                p2--;
        }
        printf("str:%s\n", str);

        system("pause");
}
页: [1]
查看完整版本: 007-字符串的三种典型模型