闲着无聊,自己写了个几个string.h里的函数练手
1. strtok 没有考虑执行效率问题,代码质量也比较差,不过基本算是完成了任务
static bool check( char c, const char *token ); char *strtok( char *str, const char *token ) { int len; static char *cur = 0; static char *next = 0; if ( token == 0 ) return str; if ( str == 0 ) { if ( next == 0 ) return 0; cur = next; len = xl::strlen( cur ); } else { len = xl::strlen( str ); cur = str; } for ( int i = 0; i < len; i++ ) { if ( check( cur[i], token ) ) { cur[i] = '\0'; next = &cur[i+1]; return cur; } } char * ret = next; next = 0; cur = 0; return ret; } static bool check( char c, const char *token ) { int len = xl::strlen( token ); for ( int i = 0; i < len; i++ ) { if ( c == token[i] ) return true; } return false; }
2. strncpy,模仿写的,不过感觉代码还有优化的空间,自己没太多的测试
主要是从2个角度进行的优化
(1) 32bit内存边界对齐
(2) 机器字长内容复制
ps. 也许写memcpy函数会更好
char * strncpy( char *dest, const char *src , int _len ) { char *ret = dest; long n = (sizeof(long) - (long)dest % sizeof(long)) % sizeof(long); long len = _len - n; if ( len > 0 ) { for ( long i = 0; i < n; i++ ) *dest++ = *src++; } else if( len < 0 ){ for ( long i = 0; i < _len; i++ ) *dest++ = *src++; return ret; } while( len >= 4 ) { *((long *)dest) = *((long *)src); dest += sizeof(long); src += sizeof(long); len -= 4; } while( len > 0 ) { *dest++ = *src++; len--; } return ret; }