您的位置:首页 > 其它

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

2011-09-13 23:27 155 查看
#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.
*/
int
substr( char dst[], char src[], int start, int len )
{
int
srcindex;
int
dstindex;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dst null include string
相关文章推荐