WIP strrepl impl

FossilOrigin-Name: b5262d6161a7e3497069831702bc33e56defb611acf1fbad367f26612d906366
This commit is contained in:
me@ow.nekobit.net 2022-04-18 19:31:35 +00:00
parent 434e68c3e2
commit 3a365b44ce
4 changed files with 33 additions and 2 deletions

View file

@ -16,6 +16,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <stddef.h>
#include <string.h>
#include "string.h"
@ -50,3 +51,25 @@ char* strnstr(const char* haystack, const char* needle, size_t s)
return NULL;
}
char* strrepl(char* source, char* find, char* repl)
{
size_t repl_len = strlen(repl);
char* result = NULL;
char* n;
char* needle = source;
do
{
n = strstr(find);
if (!n) break;
result = realloc(result, n - source + repl_len + 1);
result[n - source + repl_len] = '\0';
// Copy initial string up to here
strncpy(result, find, n - source - 1);
} while (n);
// Return source string if no replacements
return result ? result : source;
}

View file

@ -23,5 +23,6 @@
int streql(char* cmp1, char* cmp2);
int strneql(char* cmp1, char* cmp2, size_t cmp1_n);
char* strnstr(const char* haystack, const char* needle, size_t s);
char* strrepl(char* source, char* find, char* replace);
#endif // TREE_STRING_H

View file

@ -22,11 +22,12 @@
// Imports
#include "mime_multipart.c"
#include "string_test.c"
int main()
{
struct test tests[] = {
{ "Mime multipart parser", mime_multipart_test }
{ "Mime multipart parser", mime_multipart_test },
{ "Strings", string_replace_test }
};
return iterate_tests(tests, sizeof(tests)/sizeof(tests[0]));
}

6
test/unit/string_test.c Normal file
View file

@ -0,0 +1,6 @@
int string_replace_test(void)
{
strrepl
return 0;
}