extract substring – C

#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));
   printf("substring = \"%s\"\n", substring(4, 13, text, b, sizeof b));
   return 0;
}

/* my output
substring = "quick bro"
substring = "quic"
*/

http://www.linuxquestions.org/questions/programming-9/extract-substring-from-string-in-c-432620/

Published by

G3n1k

just to remember what i had known :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s