ft_strtrim - chanhl22/libft GitHub Wiki

  1 /* ************************************************************************** */          
  2 /*                                                                            */
  3 /*                                                        :::      ::::::::   */
  4 /*   ft_strtrim.c                                       :+:      :+:    :+:   */
  5 /*                                                    +:+ +:+         +:+     */
  6 /*   By: chanhlee <[email protected].>       +#+  +:+       +#+        */
  7 /*                                                +#+#+#+#+#+   +#+           */
  8 /*   Created: 2021/01/28 21:33:51 by chanhlee          #+#    #+#             */
  9 /*   Updated: 2021/01/28 21:40:39 by chanhlee         ###   ########.fr       */
 10 /*                                                                            */
 11 /* ************************************************************************** */
 12 
 13 #include "libft.h"
 14 
 15 char    *ft_strtrim(char const *s1, char const *set)
 16 {
 17     size_t  begin; //๋ฌธ์ž๋ฅผ ์ œ๊ฑฐํ•˜๊ธฐ ์œ„ํ•ด์„œ ์‹œ์ž‘ ํฌ์ธํŠธ์™€ ๋ ํฌ์ธํŠธ๋ฅผ ์žก๋Š”๋‹ค
 18     size_t  end;
 19     char    *result;
 20     int     i;
 21 
 22     if (!s1)
 23         return (NULL);
 24     if (!set)
 25         return (ft_strdup(s1)); //๋ฐ˜ํ™˜ํ•˜๋ฉด ๊ทธ๋Œ€๋กœ ๋‚˜์™€์•ผํ•จ
 26     begin = 0;
 27     while (s1[begin] != '\0' && ft_strchr(set, s1[begin])) //๋ฌธ์ž์—ด ๋‚ด์— ์ผ์น˜ํ•˜๋Š” ๋ฌธ์ž๊ฐ€ ์žˆ๋Š”์ง€ ๊ฒ€์‚ฌ (์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด NULL๋ฐ˜ํ™˜)
 28         begin++;
 29     end = ft_strlen(s1);
 30     while (end > start && ft_strchr(set, s1[end - 1])) //์ธ๋ฑ์Šค๋ฅผ ์ฐพ์„๋•Œ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋‹ˆ 1์„ ๋นผ์•ผํ•จ, ๋ฌธ์ž ์ผ์น˜ ๊ฒ€์‚ฌ
 31     {
 32         end--;
 33     }
 34     if (!(result = (char*)malloc(sizeof(char) * (end - begin + 1))))  //ํ• ๋‹น์„ ํ•ด์คŒ
 35         return (NULL);
 36     i = 0;
 37     while (begin < end) //end๊ฐ€ ๋” ํด๋•Œ ๋ฌธ์ž๋ฅผ ๋ณต์‚ฌํ•ด์•ผํ•œ๋‹ค.
 38         result[i++] = s1[start++];
 39     result[i] = '\0';
 40     return (result);
 41 }