Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

common/str.c, include/str.h: introduce str_concat() #2476

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions common/str.c
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
#include <strings.h> /* for strncasecmp() and strcasecmp() */
#endif

#include <stdarg.h> /* get the va_* routines */

#include "nut_stdint.h"
#include "str.h"

Expand Down Expand Up @@ -627,3 +629,40 @@ int str_ends_with(const char *s, const char *suff) {

return (slen >= sufflen) && (!memcmp(s + slen - sufflen, suff, sufflen));
}

/* Based on code by "mmdemirbas" posted "Jul 9 '12 at 11:41" to forum page
* http://stackoverflow.com/questions/8465006/how-to-concatenate-2-strings-in-c
* This concatenates the given number of strings into one freshly allocated
* heap object; NOTE that it is up to the caller to free the object afterwards.
*/
char * str_concat(size_t count, ...)
{
va_list ap;
size_t i, len, null_pos;
char* merged = NULL;

/* Find required length to store merged string */
va_start(ap, count);
len = 1; /* room for '\0' in the end */
for(i=0 ; i<count ; i++)
len += strlen(va_arg(ap, char*));
va_end(ap);

/* Allocate memory to concat strings */
merged = (char*)calloc(len,sizeof(char));
if (merged == NULL)
return merged;

/* Actually concatenate strings */
va_start(ap, count);
null_pos = 0;
for(i=0 ; i<count ; i++)
{
char *s = va_arg(ap, char*);
strcpy(merged+null_pos, s);
null_pos += strlen(s);
}
va_end(ap);

return merged;
}
4 changes: 4 additions & 0 deletions include/str.h
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ char *strsep(char **stringp, const char *delim);
#define HAVE_STRSEP 1
#endif

/* Concatenates "count" strings into a dynamically allocated object which
* the caller can use and must free() later on */
char * str_concat(size_t count, ...);

#ifdef __cplusplus
/* *INDENT-OFF* */
}
Expand Down
Loading