advent-of-c-ode/libs/utils.c

41 lines
797 B
C

#include "utils.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strreplace(char *s, const char *s1, const char *s2) {
char *p = strstr(s, s1);
while (p != NULL){
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
if (len1 != len2){
memmove(p + len2, p + len1, strlen(p + len1) + 1);
}
memcpy(p, s2, len2);
p = strstr(s, s1);
}
return s;
}
char *trimwhitespace(char *str){
char *end;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
// Write new null terminator character
end[1] = '\0';
return str;
}