- 论坛徽章:
- 0
|
这样写可能更好!
char *substr(char *desc,const char *src,int offset, int n_size)
{
//这段不变
if (offset< 1)
return NULL;//illegal
if (n_size< 1)
return NULL;//illegal
if ((offset+ n_size- 1) > strlen(src))
return NULL;//illegal
assert( src!= NULL);
//-------------------
char *pc =desc;
int n_StrCount=0;
while(n_StrCount<offset)
{
++src;
n_StrCount++;
}
n_StrCount=0;
while (n_StrCount<n_size)
{
*pc++=*src++;
n_StrCount++;
}
*pc='\0';
return(desc);
}
//注意
desc必须先分配好..不能指空地址NULL
如在main()定义为如下格式
char t[n_size];
或者
char *t;
t=new char[n_size+1];
//(或者)
t=(char*)malloc(sizeof(char)*n_size+1)
char *t1=new char[n_size+1];
//调用如下
t1=substr(t,"I love china",2,4);
//将得到
t1="love"
t ="love"
[ 本帖最后由 bain8181 于 2006-9-5 23:41 编辑 ] |
|