feat(string_utils): insert_into
This commit is contained in:
parent
0c9c5dc1f8
commit
df7cc02eb9
3 changed files with 121 additions and 1 deletions
|
|
@ -1,7 +1,8 @@
|
|||
#include "string_utils.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stddef.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
char *trim_blank_left(char *str)
|
||||
{
|
||||
|
|
@ -13,3 +14,31 @@ char *trim_blank_left(char *str)
|
|||
|
||||
return str;
|
||||
}
|
||||
|
||||
char *insert_into(char *dest, const char *src, size_t pos, size_t len)
|
||||
{
|
||||
size_t res_len = strlen(dest);
|
||||
size_t prefix_len = pos;
|
||||
size_t suffix_len = res_len - (pos + len);
|
||||
size_t src_len = strlen(src);
|
||||
size_t new_len = prefix_len + src_len + suffix_len;
|
||||
|
||||
if (dest == NULL || src == NULL || pos + len > res_len)
|
||||
return NULL;
|
||||
|
||||
if (res_len < new_len)
|
||||
{
|
||||
char *p = realloc(dest, new_len + 1);
|
||||
if (p == NULL)
|
||||
return NULL; // allocation failure
|
||||
dest = p;
|
||||
}
|
||||
|
||||
memmove(dest + pos + src_len, dest + pos + len, suffix_len);
|
||||
memcpy(dest + pos, src, src_len);
|
||||
dest[new_len] = 0;
|
||||
|
||||
if (res_len > new_len)
|
||||
return realloc(dest, new_len + 1);
|
||||
return dest;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,4 +12,10 @@
|
|||
*/
|
||||
char *trim_blank_left(char *str);
|
||||
|
||||
/**
|
||||
* Inserts a substring into a destination string at a specified position,
|
||||
* replacing a specified length of characters.
|
||||
*/
|
||||
char *insert_into(char *dest, const char *src, size_t pos, size_t len);
|
||||
|
||||
#endif /* STRING_UTILS_H */
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue