Thread: Copying part of a string

  1. #1
    Registered User
    Join Date
    Nov 2002
    Posts
    7

    Copying part of a string

    Say you read a string from a file:

    aaaabbbbccccdddd

    and no matter what the contents of the string you wish to copy the 5th through the 10th characters or maybe the 2nd through the 8th. In my example the 5th through the 10th characters would give "bbbbcc".

    Is there a function similar to strncpy() that you can use, or is this something that you just have to throw some code together for to do? I have searched around and come up empty on the functions but figure its worth a shot to ask because this seems like something that would be in one of the libraries.

  2. #2
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    If you use an std::string object, you can use the string::substr() method. Otherwise, something like this would work:

    Code:
    char *sub_str(char *string, int first, int last)
    {
          if (first >= last) return NULL;
          char *returnchar = new char[last-first+1];
          for (int i = 0; i <= last-first; i++)
                returnchar[i] = string[i+first];
    
          returnchar[last-first+1] = '\0';
          return returnchar;
    }
    Don't forget to free the memory with delete[]
    Last edited by Eibro; 11-20-2002 at 10:13 PM.

  3. #3
    Registered User
    Join Date
    Nov 2002
    Posts
    7
    substr() works great.

    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Copying a string, into a string array.
    By m.mixon in forum C Programming
    Replies: 5
    Last Post: 07-31-2006, 05:19 PM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM