ft_strmapi

one·2021년 1월 29일
0

✅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);
}

💡Function Pointer (출처 : 코딩도장 https://www.youtube.com/watch?v=0951M7WYuK4)

#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)); //30

	fp = mul;
	printf("%d\n", fp(10, 20)); //200
}

profile
늘 호기심을 갖고, 새로운 것에 도전할 것.

0개의 댓글