Thread: extracting a substring based on position

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    39

    Exclamation extracting a substring based on position

    Hi Lets say i have a string "ABCDEFGHIJKLMN"

    and my requirment is that i need to extract a substring from position 5-10 of the string. how do i do it in C? (i.e FGHIJK)

    Thanks

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    If you're allowed to smash the original string, then just put a null-terminator at 10 and return from 5.

    i.e.,
    Code:
    char * substr(char * str, size_t from, size_t to)
    {
       size_t len = strlen(str);
    
       if(from > len || to > len)
          return NULL;
    
       // end the string at to
       str[to] = '\0';
    
       return &str[from];
    }
    Of course if you don't want to modify the original string, then just use memcpy() in the same sort of fashion. Allocating memory for the substring before you copy it in, (from - to) characters, starting from &str[from].
    Last edited by zacs7; 06-22-2009 at 01:10 AM. Reason: WTF, strncpy()? You mean memcpy(). Noob.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You mean like memcpy?
    Code:
    memcpy( tohere, fromhere, len );
    tohere[ len ] = '\0';
    You could of course actually TRY.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need help with creating a substring program
    By CProgramingBegg in forum C Programming
    Replies: 9
    Last Post: 02-06-2009, 09:50 AM
  2. Button handler
    By Nephiroth in forum Windows Programming
    Replies: 8
    Last Post: 03-12-2006, 06:23 AM
  3. Problem with linked list ADT and incomplete structure
    By prawntoast in forum C Programming
    Replies: 1
    Last Post: 04-30-2005, 01:29 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. LISP (DrScheme) any one?
    By Jeremy G in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 03-31-2004, 12:52 PM