字符分割,把字符串按分隔符变成数组

来源:互联网 发布:电脑录像监控软件 编辑:程序博客网 时间:2024/04/24 22:34

int Parse_Msg (char *line,char **argv, int count)
{
 unsigned char *p1, *p2;
 int i;
 
 p1 = (unsigned char*)line;
 i = 0;
 while (1)
 {
  while (*p1 && *p1 <= ' ')
   p1++;
  if (*p1 == 0)
  {
   break;
  }
  argv[i++] = (char *)p1;
  if (i >= count)
   break;
  p2 = p1;
  while (*p2 && *p2 != ' ')
   p2++;
  if (*p2)
  {
   *p2 = 0;
   p1 = p2 + 1;
  }
  else
  {
   break;
  }
 }
 return i;
}

char *line:输入字符串

char **argv:输出的字符串数组

int count:最多分割为几个字符串,最后一个字符串中即使还包含分割符,也不分了。

返回值:分割得到字符串,即字符串数组的大小

-------------------------------------------------------------------------------------------------

把分割符也带入到参数中,优化一下:

 int Parse_Msg (char *line,char **argv, char dsp,int count)
{
 unsigned char *p1, *p2;
 int i;
 
 p1 = (unsigned char*)line;
 i = 0;
 while (true)
 {
  while (*p1 && *p1 <= dsp)
   p1++;
  if (*p1 == 0)
  {
   break;
  }
  argv[i++] = (char *)p1;
  if (i >= count)
   break;
  p2 = p1;
  while (*p2 && *p2 != dsp)
   p2++;
  if (*p2)
  {
   *p2 = 0;
   p1 = p2 + 1;
  }
  else
  {
   break;
  }
 }
 return i;
}

原创粉丝点击