Merge C strings to a new one

M

This code snippet provides an essential functionality to merge c strings. Using the build-in c-string function strcpy we are able to merge a lot of different strings to one without worrying about the available memory space.

This function requires the Linux Library va_args 

char * str_merge(int count, ...)
{
   va_list ap;
   int i;
   char *va_tmp;
   int len = 1; 
   va_start(ap, count);
   for(i=0 ; i<count ; i++)
   {
      va_tmp = va_arg(ap,char*);
      if(va_tmp!=NULL)
         len += strlens(va_tmp);
   }
   va_end(ap);
   char *merged = (char*)calloc(sizeof(char),len);
   int null_pos = 0;
   va_start(ap, count);
   for(i=0 ; i<count ; i++)
   {
      char *s = va_arg(ap, char*);
      if(s!=NULL)
      {
         strcpy(merged+null_pos, s);
         null_pos += strlen(s);
      }
   }
   va_end(ap);
   return merged;
}

This is a simpler yet equally efficient function without the va_args library

char * str_merge(char **strs) 
{
   int counter1 = 0, counter2 = 0, length = 0;
   do
   {
      length += strlen(strs[counter1]);
   } while (strs[++counter1] != NULL);

   char *merged = (char*)malloc(sizeof(char)*(length + 1));

   strcpy(merged, strs[0]);
   for (counter2 = 1; counter2 < counter1; counter2++)
      strcat(merged, strs[counter2]);

   return merged;
}

Add comment

Categories

Tags