In this article I show you how to implement a Split string by a specific Delimiter and pass desiderated substring into dest string.

Split Function:


/**************************************************
    INPUT:
        source  : String to split
        ch      : Delimiter
        index   : Index of the substring you want to extract
    OUTPUT:
        dest    : Extracted substring
    RETURN:
        -1      : Delimiter index not found
        >-1     : Position into source string



**************************************************/
int Split(char *source,char ch,int index, char*dest)
{
  int ret,len,i,cch,m;
  char *ps,*sp,dok;
  ret=-1;
  i=0;
  m=0;
  sp=ps;
  cch=0;
  dok=0;
  dest[0]=0;
  len=strlen(source);
  if (index==0)//first element
  {
     dok=1;
     ret=0;
  }
  while(i<len)
  {
    if (dok)//finded
    {
       if( source[i]!=ch)//populate destination string
       {
          dest[m]=source[i];
          dest[++m]=0;

       }
       else
       {
         i=len;//new delimiter, end
       }

    }

    if(source[i]==ch)//finded delimiter
    {
        cch++;
        if(cch==index)//it is my index delimiter
        {
            dok=1;
            ret=i+1;//return positon of substring into source string
        }
    }
    i++;
  }
  return ret;
}

How it works:

void main()
{
    char  destination[50];
    char inputs[120];
    int ret,c;

    sprintf(inputs,"Two things are infinite:|the universe and human stupidity;|and 
    I'm not sure|about the universe! A.E.");
    printf("%s\n\n",inputs);

    for (c=0;c<5;c++)
    {
        ret=Split(inputs,'|',c,destination);
        if (ret>-1)
        {
             printf("Finded substring at:%2d <%s>\n",ret,destination);
        }
        else
             printf("Delimiter %2d not found\n",c);
    }
   getchar();
   exit(0);
}

Result of democode:
Cattura

See also:Split and Array of Strings

Advertisements