- 论坛徽章:
- 0
|
【原创】超强版 Trim 横空出世!
我写的一个trim,带测试代码。
在sco unix,ibm aix4.3.windows上测试,效果比flw兄的好一点,尤其是在aix上。在sco上就很奇怪,优化比不优化还要慢,足见sco的烂。
缺点是对库函数的实现依赖太大。
- #include <stdio.h>;
- #include <string.h>;
- #include <memory.h>;
- #include <time.h>;
- void trim1( char *str )
- {
- char *copied, *tail = NULL;
- if ( str == NULL )
- return;
- for( copied = str; *str; str++ )
- {
- if ( *str != ' ' && *str != '\t' )
- {
- *copied++ = *str;
- tail = copied;
- }
- else
- {
- if ( tail )
- *copied++ = *str;
- }
- }
- if ( tail )
- *tail = 0;
- else
- *copied = 0;
- return;
- }
- void trim2(char * str)
- {
- char * start, * end;
-
- end=str + strlen(str)-1;
- start=str;
- for(; ((end>;=start)&&((*end==' ')||(*end=='\t'))); end--);
- *(end+1)='\0';
- for(; (start<=end)&&((*start==' ')||(*start=='\t')); start++);
- if(start!=str)
- memmove(str, start, end-start+2);
- }
- int main()
- {
- char buff[10000];
- time_t time1, time2;
- int i;
-
-
- memset(buff, 'a', sizeof(buff));
- buff[0]=' ';
- buff[9998]=' ';
- buff[9999]='\0';
-
-
- time(&time1);
- for(i=0; i<50000; i++)
- {
- buff[0]=' ';
- buff[9997]='a';
- buff[9998]=' ';
- buff[9999]='\0';
- trim1(buff);
- }
- time(&time2);
- printf("%d\n", time2-time1);
-
- time(&time1);
- for(i=0; i<50000; i++)
- {
- buff[0]=' ';
- buff[9997]='a';
- buff[9998]=' ';
- buff[9999]='\0';
- trim2(buff);
- }
- time(&time2);
- printf("%d\n", time2-time1);
-
- getchar();
- return 0;
- }
复制代码 |
|