|
兄弟想从一个bufline中提取以特定字符分隔的word,写了以下的程序。
已经编译成功,可以实现了。现在有几个问题想请教一下。
1。不知道会不会由缓冲区溢出的情况。如何改进。
2。执行效率能不能再提高些。有什么好的想法。
我以前写的getword程序,效率高些,但是通用性差,我是用的是安顺序的取word的。
- //功能同strchr 在字符串s中查找第n个字符c,成功返回指向第n个字符c的指针,失败返回空指针。
- char *strnchr(char *s,int c,int n)
- {
- char *first;
- int i;
- if (n <= 0)
- { fprintf(stderr,"arguments n below 0 \n");
- return NULL;
- }
- if (n == 1)
- return strchr(s,c);
- // n => 2
- first = strchr(s,c);
- for(i = 2;i <= n;i++)
- {
- first++;
- first = strchr(first,c);
- if (first == NULL)
- break;
- }
- return first;
- }
- // 从linebuf中取出由delim分隔开的第n个word,放入wordbuf中。成功返回指向wordbuf的指针,失败返回NULL。
- char *getnword( char *linebuf,char *wordbuf,char delim, int n)
- {
- char *first, *next;
- if(!isascii(delim))
- { fprintf(stderr,"delim error\n");
- return NULL;
- }
- if (n <= 0)
- { fprintf(stderr,"n too small\n");
- return NULL;
- }
- if (n == 1)
- {
- first = strchr(linebuf,delim);
- if (first == NULL)
- {
- strcpy(wordbuf,linebuf);
- return wordbuf;
- }
- strncpy(wordbuf,linebuf,first-linebuf);
- wordbuf[first-linebuf] = '\0';
- return wordbuf;
- }
- //n => 2
- if((first = strnchr(linebuf,delim,n-1)) == NULL)
- {
- fprintf(stderr,"not enough word separated by delim\n");
- return NULL;
- }
- if((next = strnchr(linebuf,delim,n)) == NULL)
- strcpy(wordbuf,first+1);
- else
- {
- strncpy(wordbuf,first+1,next-first-1);
- wordbuf[next-first-1] = '\0';
- }
- return wordbuf;
- }
复制代码 |
|