Skip to content

Instantly share code, notes, and snippets.

@yclim95
Last active May 30, 2022 07:48
Show Gist options
  • Save yclim95/aa31cf14776daca4bff43d18dfcf2e56 to your computer and use it in GitHub Desktop.
Save yclim95/aa31cf14776daca4bff43d18dfcf2e56 to your computer and use it in GitHub Desktop.
ft_strmapi() in c
#include <stdio.h>
#include <stdlib.h>

size_t	ft_strlen(const char *s)
{
	size_t	counter;

	counter = 0;
	while(s[counter] != '\0')
		counter++;
	return (counter);
}

char    test(unsigned int i, char str)
{
    printf("My inner function: index = %d and %c\n", i, str);
    return (str);
}

char    test2(unsigned int i, char str)
{
    printf("My inner function2: index = %d and %c\n", i, str);
    return (str);
}

char	*ft_strmapi(char const *s, char (*f)(unsigned int, char))
{
	size_t	len;
	size_t	c;
	char	*p_funcarg;

	len = ft_strlen(s);
	p_funcarg = malloc(sizeof(char) * (len + 1));
	if (!p_funcarg)
		return (0);
	c = 0;
	while (c < len)
	{
		p_funcarg[c] = f(c, s[c]);
		c++;
	}
	p_funcarg[len] = '\0';
	return (p_funcarg);
}

int main()
{
    char const *s1 = "Hello 42KL";
    char *p_strmapi1;
    char *p_strmapi2;
    p_strmapi1 = ft_strmapi(s1,test);
    p_strmapi2 = ft_strmapi(s1,test2);
    printf("test1: %s\n", p_strmapi1);
    printf("test2: %s\n", p_strmapi2);
    
    return 0;
}
My inner function: index = 0 and H
My inner function: index = 1 and e
My inner function: index = 2 and l
My inner function: index = 3 and l
My inner function: index = 4 and o
My inner function: index = 5 and  
My inner function: index = 6 and 4
My inner function: index = 7 and 2
My inner function: index = 8 and K
My inner function: index = 9 and L
My inner function2: index = 0 and H
My inner function2: index = 1 and e
My inner function2: index = 2 and l
My inner function2: index = 3 and l
My inner function2: index = 4 and o
My inner function2: index = 5 and  
My inner function2: index = 6 and 4
My inner function2: index = 7 and 2
My inner function2: index = 8 and K
My inner function2: index = 9 and L
test1: Hello 42KL
test2: Hello 42KL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment