Archive for the ‘ C ’ Category

Author : beriba | 02/24/2013

Fast and quick post today. If you need substring in C you can do it using this function. In the main() function you have example of usage. If you have comments, feel free to ask me.

#include <stdio.h>

char *substring(size_t start, size_t stop, const char *src, char *dst, size_t size)
{
   int count = stop - start;
   if ( count >= --size )
   {
      count = size;
   }
   sprintf(dst, "%.*s", count, src + start);
   return dst;
}

int main()
{
   static const char text[] = "The quick brown fox jumps over the lazy dog.";
   char a[10], b[5];
   printf("substring = \"%s\"\n", substring(4, 13, text, a, sizeof a)); /* substring = "quick bro" */
   printf("substring = \"%s\"\n", substring(4, 13, text, b, sizeof b)); /* substring = "quic" */
   return 0;
}