C实现substr[原创]

标签: c 原型 substr C/C++

C实现substr[原创]

帖子NT流人 于 2010年 7月 16日 11:42

简单实现substr,c里面好像没有这个函数。
代码: 全选
#include <stdio.h>
#include <assert.h>

char *substr(char *destination, const char *source, int start,int length);
int strlen(const char *source);

int main(void) {
        char strA[80] = "HelloWorld";
        char strB[80];
        substr(strB,strA,1,3);
        puts(strB);
        return 1;
}

char *substr(char *destination, const char *source, int start, int length) {
        assert((destination != NULL) && (source != NULL));
        assert(start > 0 && length > 0);
        assert((start + length) <= strlen(source));

        char *tmpAddress = destination;
        int i;
        int end = start + length;
        for (i = start; i < end; i++) {
                *destination++ = *(source + i);
        }
        *destination = '\0';
        return tmpAddress;
}

int strlen(const char *source) {
        assert(source != NULL);
        int length;
        while (*source++ != '\0') {
                length++;
        }
        return length;
}
在指尖流浪
1. Everything changes and ends. 所有的事情在变化,都有终结
2. Things do not always go according to plan. 事情总会出乎意料(计划)之外
3. Life is not always fair. 生活并不总是公平
4. Pain is part of life. 痛苦是生活的一部分
5. People are not loving and loyal all the time. 人们并不总是热爱和忠诚
头像
NT流人
网站管理员
 
帖子: 744
加入时间: 2008年 1月 2日 13:15

回到 C/C++

在线用户

正在浏览此版面的用户:没有注册用户 和 1 位游客

cron