ft_strtrim 구현

yeonjkim·2021년 5월 25일
0

42seoul-libft

목록 보기
32/43

1. ft_strtrim 용도

* ft_strtrim은 파라미터로 s1 문자열과 set 문자열을 갖는다.

* 's1의 왼쪽에서 set이 아닌 문자가 나올 때'부터 's1의 오른쪽에서 set이 아닌 문자가 나올 때'까지 자르는 함수이다.

2. ft_strtrim 프로토타입

char	*ft_strtrim(char const *s1, char const *set)
char const *s1 : set으로 잘라지는 문자열
char const *set : 나누는 기준이 되는 문자열

3. 구현 시 유의사항

  • 만약 s1에 set이 아닌 문자가 없다면 반환할 str에 1만큼을 할당해주고, 할당한 메모리에 0을 넣고 str을 리턴한다.

  • 할당에 실패했다면 NULL을 반환한다.

  • 반환할 문자열의 끝에는 '\0'문자가 들어 있어야 한다.

4. 코드 구현

#include "libft.h"

static int              ft_isin(char find, char const *str)//find문자가 str문자열 안에 들어 있으면 1리턴, 없으면 0리턴.
{
        int             index;

        index = 0;
        while (str[index] != '\0')
        {
                if (find == str[index])
                {
                        return (1);
                }
                index++;
        }
        return (0);
}

static int              ft_findstart(char const *s1, char const *set)//시작 부분을 찾는 함수.
{
        int             index;

        index = 0;
        while (s1[index] != '\0')
        {
                if (ft_isin(s1[index], set) == 0)
                {
                        return (index);
                }
                index++;
        }
        return (-1);//set이 아닌 문자가 s1안에 없으면 -1리턴
}

static int              ft_findend(char const *s1, char const *set)//끝 부분을 찾는 함수
{
        int             index;

        index = (int)(ft_strlen(s1)) - 1;
        while (index >= 0)
        {
                if (ft_isin(s1[index], set) == 0)
                {
                        return (index);
                }
                index--;
        }
        return (-1);//set이아닌 문자가 s1안에 없으면 -1리턴
}

char                    *ft_strtrim(char const *s1, char const *set)
{
        int             start;
        int             end;
        char    *str;
        int             index;

        str = NULL;
        index = 0;
        start = ft_findstart(s1, set);
        end = ft_findend(s1, set);
        if (start == -1 || end == -1)//set이 아닌 문자가 s1안에 없으면
        {
                str = (char*)malloc(1);//1만큼 할당
                str[0] = 0;//할당한 메모리에 0넣기
                return (str);//반환
        }
        if (!(str = (char*)malloc(sizeof(char) * (end - start + 2))))
                return (NULL);
        while (start <= end)
                str[index++] = s1[start++];
        str[index] = '\0';
        return (str);
}

5. 함수별 코드 구현 방법

1 ) ft_isin() : 인자로 find문자와 str문자열을 받는다.
str문자열이 결국 set문자열이고, find문자는 s1의 값들인데, 결국 s1[index]가 set인지 검사해서 set이면 1, set이 아니면 0을 반환한다.
2 ) ft_findstart() : s1의 왼쪽부터 탐색해 set이 아닌 문자가 있는 s1의 인덱스를 반환하는 함수.
set이 아닌 문자가 없으면 -1을 반환
3 ) ft_findend() : s1의 오른쪽부터 탐색해 set이 아닌 문자가 있는 s1의 인덱스를 반환하는 하뭇.
set이 아닌 문자가 없으면 -1을 반환
4 ) ft_strtrim() : start와 end를 받아 trim을 진행.
만약 start나 end가 -1이면, 즉 set이 아닌 문자가 s1에 없으면 str에 1만큼 할당하고, 그 할당한 메모리에 0을 채우고 리턴.
start와 end가 -1이 아니면 (end - start + 2)('\0' 포함)만큼 할당하고 str에 값을 채우고 '\0'넣고 리턴.

0개의 댓글