Created
September 13, 2011 00:05
-
-
Save dbspringer/1212828 to your computer and use it in GitHub Desktop.
Substring in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <string.h> | |
void substr (const char *inpStr, char *outStr, size_t startPos, size_t strLen) { | |
/* Cannot do anything with NULL. */ | |
if (inpStr == NULL || outStr == NULL) return; | |
/* All negative positions to go from end, and cannot | |
start before start of string, force to start. */ | |
if (startPos < 0) { | |
startPos = strlen (inpStr) + startPos; | |
} | |
if (startPos < 0) { | |
startPos = 0; | |
} | |
/* Force negative lengths to zero and cannot | |
start after end of string, force to end. */ | |
if (strLen < 0) { | |
strLen = 0; | |
} | |
if (startPos > strlen (inpStr)) { | |
startPos = strlen (inpStr); | |
} | |
/* Adjust length if source string too short. */ | |
if (strLen > strlen (&inpStr[startPos])) { | |
strLen = strlen (&inpStr[startPos]); | |
} | |
/* Copy string section */ | |
strncpy(outStr, inpStr+startPos, strLen); | |
outStr[strLen] = '\0'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment