Skip to content

Instantly share code, notes, and snippets.

@dbspringer
Created September 13, 2011 00:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 <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