In this post I show you how to implement Left,Mid and Right Functions with unique function to extrapolate part of source string.

These are the defines to use with function

 

#define LEFT(source,n)   LMR(source,0,n,0)
#define MID(source,s,n)  LMR(source,s,n,0)
#define RIGHT(source,n)  LMR(source,0,n,1)

Left, Mid and Right Function

 

/***

INPUT
    source      :     source string
    start       :     Character position in source to start to take
    len         :     Number of characters to take
    Mode        :     if equal 1 implement Right function otherwise Left or Mid function
RETURN
                      Substring of source
****/
char* LMR(char* source,int start,int len,char mode)
{
    char *s;
    int loclen;

    loclen=strlen(source);
    if(len>0 && loclen>0)
    {
        s=malloc(len+1);
        if (start<0)
            start=0;

        if(mode==1)//Right function
           start=(loclen-len);

        if ((start+len)<=loclen)
        {
           memcpy(s,source+start,len);
           s[len]=0;
        }
        else
           s=NULL;
    }

    return s;
}

Demonstration how to use thifunction with the defines

int main()
{
  char s[50];
  sprintf(s,"%s","Good Morning World");
  printf("Test String <%s>\n\nResult:\n",s);
  printf(" Left String <%s>\n",LEFT(s,4));
  printf("  Mid String <%s>\n",MID(s,5,7));
  printf("Right String <%s>\n",RIGHT(s,5));
  getchar();
  exit(0);
}

Generated Output:

Cattura2

See also:PadLeft and PadRight Function

Advertisements