strtrim

유제민·2025년 4월 10일

42경산

목록 보기
11/17

strtrim 뭐예여

문자열 양쪽 끝에 있는 특정 문자들을 잘라내서 새로운 문자열을 만드는 함수

함수 원형: char strtrim(char const s1, char const *set)
char const *s1: 원본 문자열
char const *set: 잘라낼 특정 문자열
만약 s1 == "!!~hello world!~~!", set == "!~"이라면 "hello world"가 되는 것!

ft_strtrim 구현

#include "libft.h"

char	*ft_strtrim(char const *s1, char const *set)
{
	size_t		start;
	size_t		end;
	size_t		len;
	size_t		i;
	char		*result;

	if (!s1 || !set)
		return (NULL);
	start = 0;
	end = ft_strlen(s1);
	while (s1[start] && ft_strchr(set, s1[start]))	//원본 문자열 앞에 set 문자 제거
		start++;
	if (end > 0)
		end--;
	while (end > start && ft_strchr(set, s1[end - 1]))	//원본 문자열 뒤에 set문자 제거
		end--;
	len = end - start + 1; //set문자 제외한 원본 문자열의 길이를 저장 + NULL 들어갈 공간
	result = (char *)malloc(sizeof(char) * (end - start + 1));
	if (!result)
		return (NULL);
	i = 0;
	while (start < end)
		result[i++] = s1[start++];
	result[i] = '\0';
	return (result);
}
profile
무진장 게으른

0개의 댓글