Skip to content

Instantly share code, notes, and snippets.

@dbspringer
Created September 13, 2011 00:05
Show Gist options
  • Save dbspringer/1212828 to your computer and use it in GitHub Desktop.
Save dbspringer/1212828 to your computer and use it in GitHub Desktop.
Substring in C
#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