Created
September 13, 2011 00:05
-
-
Save dbspringer/1212828 to your computer and use it in GitHub Desktop.
Substring in C
This file contains 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 <stdio.h> | |
#include <string.h> | |
/* If you're feeling sassy, a macro one-liner w/out checks */ | |
#define substr(dest, src, dest_size, startPos, strLen) snprintf(dest, dest_size, "%.*s", strLen, src+startPos) | |
/* Python-like idiom of negative values to count from the end of the string. */ | |
void substr (char *dest, const char *src, int startPos, size_t strLen) { | |
/* Cannot do anything with NULL. */ | |
if (dest == NULL || src == NULL) return; | |
size_t len = strlen (src); | |
/* All negative positions to go from end, and cannot | |
start before start of string, force to start. */ | |
if (startPos < 0) { | |
startPos = len + startPos; | |
} | |
if (startPos < 0) { | |
startPos = 0; | |
} | |
/* Force negative lengths to zero and cannot | |
start after end of string, force to end. */ | |
if ((size_t)startPos > len) { | |
startPos = len; | |
} | |
len = strlen (&src[startPos]); | |
/* Adjust length if source string too short. */ | |
if (strLen > len) { | |
strLen = len; | |
} | |
/* Copy string section */ | |
memcpy(dest, src+startPos, strLen); | |
dest[strLen] = '\0'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment