Sha256: f783a8efb77f994fbe8f1a1b5b2d8b4680185a711063e769bf7ce232cc2b5dac
Contents?: true
Size: 1.62 KB
Versions: 3
Compression:
Stored size: 1.62 KB
Contents
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "string_extras.h" void remove_last_char(char* str) { size_t len = strlen(str); str[len - 1] = '\0'; } void remove_first_char(char* str) { size_t len = strlen(str); memmove(str, str + 1, len); } char *dupe_string(const char * str) { int len = strlen(str) + 1; char *buf = malloc(len); if (buf) { memcpy(buf, str, len); } return buf; } char *dupe_string_n(const char *s, size_t n) { char* buf = malloc(n + 1); if (buf) { strncpy(buf, s, n); buf[n] = '\0'; } return buf; } char * str_replace (char *string, const char *substr, const char *replacement) { char *tok = NULL; char *newstr = NULL; char *oldstr = NULL; /* if either substr or replacement is NULL, duplicate string a let caller handle it */ if ( substr == NULL || replacement == NULL ) { return dupe_string (string); } newstr = dupe_string (string); while ( ( tok = strstr( newstr, substr ) ) ) { oldstr = newstr; newstr = malloc ( strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1 ); /* If failed to alloc mem, free old string and return NULL */ if ( newstr == NULL ) { free (oldstr); return NULL; } memcpy ( newstr, oldstr, tok - oldstr ); memcpy ( newstr + (tok - oldstr), replacement, strlen ( replacement ) ); memcpy ( newstr + (tok - oldstr) + strlen( replacement ), tok + strlen ( substr ), strlen ( oldstr ) - strlen ( substr ) - ( tok - oldstr ) ); memset ( newstr + strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) , 0, 1 ); free (oldstr); } return newstr; }
Version data entries
3 entries across 3 versions & 1 rubygems