1、问题引入
自己在写一个linux下的模拟执行指令的时候,遇到了输入"cat a.c”,要将该字符串分解成cat和a.c两个单独的字符串,虽然知道有strtok的存在,但是想自己尝试写一下,于是就自己写了一个,不过总是遇到这样或那样的问题,虽然最后调通了,不过确浪费了不少时间;后来作业交上去以后又仔细阅读了strtok函数,发现原来linux下已经改成strsep,所有在这里就写一下自己所走的过程。
2、自己写的字符串分割函数:用于分割指令,比如cat a.c最后会被分割成cat和a.c两个字符串、mv a.c b.c最后会被分割成mv和a.c和b.c三个字符串。
具体实现如下:
1 #include <stdio.h> 2 #include<string.h> 3 #define MAX_LEN 128 4 void main() 5 { 6 int i,length,ct=0,start = -1; 7 char inputBuffer[MAX_LEN],*args[MAX_LEN]; 8 strcpy(inputBuffer,"mv a.c b.c"); 9 length=strlen(inputBuffer);10 for (i = 0; i <= length; i++) {11 switch (inputBuffer[i]){12 case ' ':13 case '\t' : /* argument separators */ 14 if(start != -1){15 args[ct] = &inputBuffer[start]; /* set up pointer */ 16 ct++;17 }18 inputBuffer[i] = '\0'; /* add a null char; make a C string */ 19 start = -1;20 break;21 case '\0': /* should be the final char examined */ 22 if (start != -1){23 args[ct] = &inputBuffer[start];24 ct++;25 }26 inputBuffer[i] = '\0';27 args[ct] = NULL; /* no more arguments to this command */ 28 break;29 default : /* some other character */ 30 if (start == -1)31 start = i;32 }33 }34 printf("分解之后的字符串为:\n");35 for(i=0;i<ct;i++)36 printf("%s \n",args[i]);37 }
3、作业提交后又查询了strtok,发现使用strtok函数会方便很多
具体示例如下:
#include <stdio.h> #include<string.h>int main()
{
char str[] = "mv a.c b.c";
char *p;
p = strtok(str, " ");
while(p)
{
printf("%s\n", p);
p = strtok(NULL, " ");
}
return 0;
}
4、在linux2.6.29以后的版本中,strtok被strsep代替了。
具体示例如下:
1 #include <stdio.h> 2 #include<string.h> 3 int main() 4 { 5 char str[] = "mv a.c b.c"; 6 char *p; 7 char *buff; 8 buff=str; 9 p = strsep(&buff, " ");10 while(p)11 {12 printf("%s\n", p);13 p = strsep(&buff, " ");14 }15 return 0;16 }
而且在我自己的电脑的linux中的codeblog下,运行4中代码需要0.029s,而运行3中的代码需要0.044s,说明strsep速度确实比strtok快一些,,
转载自:http://www.cnblogs.com/lpshou/archive/2012/06/04/2534376.html。