zoukankan      html  css  js  c++  java
  • C中的字符串实例

    1.#include <stdio.h>
    #include <assert.h>

    size_t strlen(const char* s)
    {
        return ( assert(s), (*s ? (strlen(s+1) + 1) : 0) );
    }

    int main()
    {
        printf("%d ", strlen( NULL));
        
        return 0;
    }

    2.#include <stdio.h>
    #include <assert.h>

    char* strcpy(char* dst, const char* src)
    {
        char* ret = dst;
        
        assert(dst && src);//断言一定要调用assert,这是安全编程的思想,错误处理的思想
        
        while( (*dst++ = *src++) != '' );
        
        return ret;
    }

    int main()
    {
        char dst[20];
        
        printf("%s ", strcpy(dst, "Delphi Tang!"));
        getch();    
        return 0;

    }

    3.#include <stdio.h>
    #include <malloc.h>

    int main()
    {
        char s1[] = {'H', 'e', 'l', 'l', 'o'};
        char s2[] = {'H', 'e', 'l', 'l', 'o', ''};
        char* s3 = "Hello";          //只读存储区
        char* s4 = (char*)malloc(6*sizeof(char)); //堆
        
        s4[0] = 'H';
        s4[1] = 'e';
        s4[2] = 'l';
        s4[3] = 'l';
        s4[4] = 'o';
        s4[5] = '';
        
        free(s4);
        
        return 0;
    }

    4.#include <stdio.h>
    #include <assert.h>

    size_t strlen(const char* s)
    {
        size_t length = 0;
        
        assert(s);
        
        while( *s++ )
        {
            length++;
        }
        
        return length;
    }

    int main()
    {
        printf("%d ", strlen("123456789"));
        
        return 0;
    }

  • 相关阅读:
    洛谷P3258 [JLOI2014]松鼠的新家
    洛谷P3128 [USACO15DEC]最大流Max Flow
    Bzoj1651: [Usaco2006 Feb]Stall Reservations 专用牛棚
    2017-9-26 NOIP模拟赛
    洛谷P1441 砝码称重
    洛谷P1275 魔板
    洛谷P2037 电话号码
    2014-11-3 NOIP模拟赛2
    洛谷P3102 [USACO14FEB]秘密代码Secret Code
    洛谷P3070 [USACO13JAN]岛游记Island Travels
  • 原文地址:https://www.cnblogs.com/wxb20/p/6150535.html
Copyright © 2011-2022 走看看