ft_strmapi

jaehlee·2025년 4월 27일

Libft

목록 보기
15/26

1.ft_strmapi란?


문자열 s의 각 요소에 함수f를 적용한 값으로 새로운 문자열을 만드는 함수이다. 새롭게 만든 문자열의 주소를 리턴한다.

2. 함수 프로토타입

char *ft_strmapi(char const *s, char (*f)(unsigned int, char))

3. 함수구현

#include "libft.h"

char	*ft_strmapi(char const *s, char (*f)(unsigned	int, char))
{
	unsigned int	len;
	unsigned int	index;
	char			*result;

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

사용예시

char	f(unsigned int i, char c)
{
	if (i % 2 == 1 && c >= 'a' && c <= 'z')
		return (c - ('a' - 'A')); // 홀수 인덱스이면서 소문자일 때만 대문자로
	return (c); 
}

int main(void)
{
	char *s = "hello42";
	char *new_s;

	new_s = ft_strmapi(s, f);
	if (!new_s)
	{
		printf("Memory allocation failed.\n");
		return (1);
	}

	printf("Original: %s\n", s);   // hello42
	printf("Modified: %s\n", new_s); // hElLo42

	free(new_s);
	return (0);
}
profile
공부하는 개발자

0개의 댓글