--- libelwix/src/str.c 2023/03/14 22:36:13 1.10 +++ libelwix/src/str.c 2024/10/28 09:58:51 1.11 @@ -3,7 +3,7 @@ * by Michael Pounov * * $Author: misho $ -* $Id: str.c,v 1.10 2023/03/14 22:36:13 misho Exp $ +* $Id: str.c,v 1.11 2024/10/28 09:58:51 misho Exp $ * ************************************************************************** The ELWIX and AITNET software is distributed under the following @@ -12,7 +12,7 @@ terms: All of the documentation and software included in the ELWIX and AITNET Releases is copyrighted by ELWIX - Sofia/Bulgaria -Copyright 2004 - 2023 +Copyright 2004 - 2024 by Michael Pounov . All rights reserved. Redistribution and use in source and binary forms, with or without @@ -522,4 +522,66 @@ str_getString2(char * __restrict data, int dlen, char if (next) *next = (char*) pos + 1; return pos - data; +} + +/* + * str_find2replace() - Search find string into data and replace + * + * @data = input string + * @find = search for string + * @replace = replace to string. If it is NULL then deletes found search string + * @str = new produced allocate string. If it is NULL then just return found occurances of find + * @mlen = allocated memory size for new string + * return: -1 error, 0 not found or >0 how many occurances we have for find string + */ +int +str_find2replace(const char *data, const char *find, const char *replace, char **str, int *mlen) +{ + int cnt = 0, data_len, slen, find_len, replace_len = 0; + const char *pos, *s; + + if (!data || !find) + return -1; + + find_len = strlen(find); + data_len = strlen(data); + for (pos = data; (pos = strstr(pos, find)); pos += find_len, cnt++); + + /* just count occurances */ + if (!str || !mlen) + return cnt; + + slen = data_len - find_len * cnt; + if (replace) { + replace_len = strlen(replace); + slen += replace_len * cnt; + } + /* alloc exports string */ + *mlen = slen + 1; + *str = e_malloc(*mlen); + if (!*str) + return -1; + else + memset(*str, 0, *mlen); + + /* search & replace */ + for (pos = data; *pos;) { + s = strstr(pos, find); + if (s) + slen = s - pos; + else + slen = strlen(pos); + /* + * This hack was made due to behaviour of compiler against strncat(*str, pos, slen)! + */ + memcpy(*str + strlen(*str), pos, slen); + if (s) { + if (replace) + strncat(*str, replace, replace_len); + pos += find_len; + } + pos += slen; + } + + return cnt; }