Thread: Substring of a string

  1. #1
    Registered User
    Join Date
    Jan 2006

    Substring of a string


    I'm fairly new to C, but I need to program a barcode scanner.

    I need a function that allows me to substract a small string from a larger string, but I want to be able to give the starting and end position.

    For example:

    String= "abcdefgh"

    I want to able to get all the letters from position 2 to 5 in the string, for example, so it will give me "bcde".

    Is this possible, because I can't find a standard function in C that will allow me to do this.

    Thanks in advance for your reply!



  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Sydney, Australia
    One solution would be to use strncpy. You can specify the amount of characters to copy, and when you specify the source string, calculate the starting offset.

    For example, for position 2 to 5, you'd use:
    strncpy(dst, src + 1, 4);
    We specify + 1 for position 2 because C arrays are zero based. The 4 is the number of characters between 2 and 5.

    Remember that strncpy will NOT null terminate the string for you (unless you copy to the end of src (not in this case)), so you'd need an additional:
    dst[4] = '\0';

    I'll leave it as an exercise for you to produce a function to do this. Example declaration:
    void slice(char *dst, char *src, int start, int finish)
    Of course dst will need to point to something capable of holding at least (finish - start + 2) elements.
    Last edited by cwr; 01-23-2006 at 08:10 AM.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Or you can use a for loop:
    int x;
    for(x = 1; x < 5; x ++) {
        printf("%c", array[x]);  /* or assign this value somewhere else */
    Or you could use printf():
    /* print a maximum of 4 chars, starting with array[1] */
    printf("%.*s", 4, array+1);
    Note: array+1 is the same as &array[1].

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell

    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ:

    My website:
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  3. String
    By maxorator in forum C++ Programming
    Replies: 8
    Last Post: 10-30-2005, 12:36 AM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM