int substr( char dst[], char src[], int start, int len )

来源:互联网 发布:淘宝的详情页怎样发布 编辑:程序博客网 时间:2024/05/17 23:19
#include <stdio.h>#include <string.h>#include <assert.h>int substr( char dst[], char const str[], int start, int len );int main(){char dst[10];char src[10] = "zhangleiy";    int  len = substr( dst, src, 2, 3 );    printf( "目的数组长度 : %d \n", len);    printf( "目的数组为   : %s \n", dst);    return 0;}int substr( char dst[], char const src[], int start, int len ){assert( dst != NULL && src != NULL );    char *temp = dst;;int dst_len = 0;int src_len = strlen( src );if( start<0 || len<=0 || src_len < start )printf( "提取位置或字符个数不符合要求 !\n" );    int i=0;for( i=0; i<start; i++ ) src++;//while( (*temp++ = *src++) != '\0' && dst_len < len )while( dst_len < len && (*temp++ = *src++) != '\0' )   // 若把比较长度放在后面,就会多复制一个字符dst_len++;    *temp = '\0';    return dst_len;}

原答案源码如下:

/*** Extract the specified substring from the string in src.*/intsubstr( char dst[], char src[], int start, int len ){intsrcindex;intdstindex;dstindex = 0;if( start >= 0 && len > 0 ){/*** Advance srcindex to right spot to begin, but stop if we reach** the terminating NUL byte.*/for( srcindex = 0;srcindex < start && src[srcindex] != ’\0’;srcindex += 1 );/*** Copy the desired number of characters, but stop at the NUL if** we reach it first.*/while( len > 0 && src[srcindex] != ’\0’ ){dst[dstindex] = src[srcindex];dstindex += 1;srcindex += 1;len –= 1;}}/*** Null–terminate the destination.*/dst[dstindex] = ’\0’;return dstindex;}