maxishell
Implementation of a shell for Linux-like systems
Loading...
Searching...
No Matches
ft_strmapi.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* ft_strmapi.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: rmikhayl <rmikhayl@student.42london.c +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2023/12/17 17:25:26 by rmikhayl #+# #+# */
9/* Updated: 2023/12/17 17:25:26 by rmikhayl ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "libft.h"
14
15/* *************************** ft_strmapi *********************************** */
16/* Applies a given function 'f' to each character of the string 's' along */
17/* with its index. Returns a new string with the modified characters. */
18/* If 's' or 'f' is NULL or memory allocation fails, returns NULL. */
19/* */
20/* Difference from ft_striteri: */
21/* - This function creates a new string with the modified characters and */
22/* returns it, while ft_striteri modifies the original string in-place. */
23/* */
24/* In layman's terms: It's like reading a text and making changes to each */
25/* letter while remembering where each letter was originally located. */
26/* ************************************************************************** */
27
28char *ft_strmapi(char const *s, char (*f)(unsigned int, char))
29{
30 char *result;
31 size_t len;
32 size_t i;
33
34 if (!s || !f)
35 return (NULL);
36 len = 0;
37 while (s[len] != '\0')
38 len++;
39 result = (char *)malloc((len + 1) * sizeof(char));
40 if (!result)
41 return (NULL);
42 i = 0;
43 while (i < len)
44 {
45 result[i] = f(i, s[i]);
46 i++;
47 }
48 result[len] = '\0';
49 return (result);
50}
char * ft_strmapi(char const *s, char(*f)(unsigned int, char))
Definition ft_strmapi.c:28