Copying part of a string
Say you read a string from a file:
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.
If you use an std::string object, you can use the string::substr() method. Otherwise, something like this would work:
Don't forget to free the memory with delete
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';
substr() works great.