✅strmapi
- Applies the function
f
to each character of the
string s
to create a new string (with malloc(3))
resulting from successive applications of f
.
s
문자열을 f
함수에 적용
💾Prototype
char *ft_strmapi(char const *s, char (*f)(unsigned int, char));
💻Parameters
s
: The string on which to iterate.
f
: The function to apply to each character.
💻Return value
- The string created from the successive applications
of f
. Returns NULL if the allocation fails.
💾Code
#include "libft.h"
char* ft_strmapi(char const* s, char (*f)(unsigned int, char))
{
size_t len;
size_t i;
char* str;
i = 0;
if (!s || !f)
return (0);
len = ft_strlen(s);
if (!(str = (char*)malloc(sizeof(char) * (len + 1))))
return (0);
while (i < len)
{
str[i] = f(i, s[i]);
i++;
}
str[i] = '\0';
return (str);
}
💾Example
#include <stdio.h>
char f(unsigned int i, char c)
{
char str;
str = c + 1;
return (str);
}
int main()
{
char str1[] = "abc";
char* str2;
str2 = ft_strmapi(str1, *f);
printf("%s\n", str2);
}
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int mul(int a, int b)
{
return a * b;
}
int main()
{
int(*fp)(int, int);
fp = add;
printf("%d\n", fp(10, 20));
fp = mul;
printf("%d\n", fp(10, 20));
}