C语⾔substr函数⽤法,⾃⼰实现substr函数——C语⾔#include
#include
#include
#include
char* mysubstr(char* srcstr, int offset, int length) {
assert(length > 0);
assert(srcstr != NULL);
int total_length = strlen(srcstr);//⾸先获取srcstr的长度
//判断srcstr的长度减去需要截取的substr开始位置之后,剩下的长度
c语言char的用法//是否⼤于指定的长度length,如果⼤于,就可以取长度为length的⼦串
//否则就把从开始位置剩下的字符串全部返回。
int real_length = ((total_length - offset) >= length ? length : (total_length - offset)) + 1;
char *tmp;
if (NULL == (tmp=(char*) malloc(real_length * sizeof(char)))) {
printf("Memory overflow . \n");
exit(0);
}
strncpy(tmp, srcstr+offset, real_length - 1);
tmp[real_length - 1] = '\0';
return tmp;
}
int main() {
char srcstr[] = "this is a test string!";
char* tmp = mysubstr(srcstr, 8, 8);
printf("TEST: result = %s\n", tmp);
free(tmp);
return 0
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论