This repository has been archived by the owner on Oct 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strreplace.c
40 lines (37 loc) · 1.59 KB
/
ft_strreplace.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_strreplace.c :+: :+: */
/* +:+ */
/* By: fbes <[email protected]> +#+ */
/* +#+ */
/* Created: 2022/02/08 21:25:13 by fbes #+# #+# */
/* Updated: 2022/02/09 17:12:16 by fbes ######## odam.nl */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "libft.h"
char *ft_strreplace(char *str, char *find, char *replace)
{
char *replaced;
char *loc;
size_t find_len;
size_t old_len;
size_t repl_len;
find_len = ft_strlen(find);
old_len = ft_strlen(str);
if (find_len == 0 || find_len > old_len)
return (ft_strdup(str));
loc = ft_strnstr(str, find, old_len);
if (!loc)
return (ft_strdup(str));
repl_len = ft_strlen(replace);
replaced = malloc((old_len - find_len + repl_len + 1) * sizeof(char));
if (!replaced)
return (NULL);
ft_memmove(replaced, str, loc - str);
ft_memmove(&replaced[loc - str], replace, repl_len);
ft_memmove(&replaced[loc - str + repl_len], &loc[find_len],
ft_strlen(&loc[find_len]) + 1);
return (replaced);
}