Skip to content

Commit

Permalink
added strcat and strjoin to strlib.
Browse files Browse the repository at this point in the history
  • Loading branch information
horacio.gomez committed Nov 29, 2011
1 parent 881aabb commit dad6bcc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
4 changes: 4 additions & 0 deletions include/lib/string.h
Expand Up @@ -104,4 +104,8 @@ char *strtok(register char *string, const char *separators);

int strreplace(char* str, char replace, char replacement);

char *strcat(char *ret, register const char *s2);

char* strjoin(char* strings[], char* seperator, int count);

#endif
33 changes: 33 additions & 0 deletions src/lib/string.c
Expand Up @@ -146,3 +146,36 @@ int strreplace(char* str, char replace, char replacement) {
}
return replaces;
}

char *strcat(char *ret, register const char *s2) {
register char *s1 = ret;

while (*s1++ != '\0')
/* EMPTY */ ;
s1--;
while ((*s1++ = *s2++))
/* EMPTY */ ;
return ret;
}

char* strjoin(char* strings[], char* seperator, int count) {
char* str = NULL; /* Pointer to the joined strings */
unsigned int total_length = 0; /* Total length of joined strings */
int i = 0; /* Loop counter */

/* Find total length of joined strings */
for (i = 0; i < count; i++) total_length += strlen(strings[i]);
total_length++; /* For joined string terminator */
total_length += strlen(seperator) * (count - 1); // for seperators

str = (char*) malloc(total_length); /* Allocate memory for joined strings */
str[0] = '\0'; /* Empty string we can append to */

/* Append all the strings */
for (i = 0; i < count; i++) {
strcat(str, strings[i]);
if (i < (count - 1)) strcat(str, seperator);
}

return str;
}

0 comments on commit dad6bcc

Please sign in to comment.