c04 - KimTaebin-ai/study_posts GitHub Wiki
02 03과 마찬가지로 string, 특히 atoi 함수를 처리하는 방법을 다루는 문제
int ft_strlen(char *str)
{
int count;
int i;
count = 0;
i = 0;
while (str[i] != '\0')
{
i++;
}
count = i;
return (count);
}
void ft_putstr(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
write(1, &str[i++], 1);
}
}
void print_char(char c)
{
write(1, &c, 1);
}
void ft_putnbr(int nb)
{
if (nb == -2147483648)
{
wrtie(1, "-2147483648", 1);
return ;
}
if (nb < 0)
{
print_char('-');
nb = -nb;
}
if (nb >= 10)
{
ft_putnbr(nb / 10);
}
print_char('0' + nb % 10);
}
int is_space(char c)
{
return (c == ' ' || c == '\n' || c == '\t' || c == '\v' || c == '\f'
|| c == '\r');
}
int ft_atoi(char *str)
{
int i;
int sign;
int result;
i = 0;
sign = 1;
result = 0;
while (is_space(str[i]))
i++;
if (str[i] == '-' || str[i] == '+')
{
if (str[i] == '-')
sign = -1;
i++;
}
while (str[i] >= '0' && str[i] <= '9')
{
result = result * 10 + (str[i] - '0');
i++;
}
return (result * sign);
}
#include <unistd.h>
int ft_len(char *base)
{
int len;
int i;
int j;
len = 0;
i = 0;
j = 0;
while (base[len] != '\0')
{
if (base[len] == '-' || base[len] == '+')
return (0);
len++;
}
while (i < len - 1)
{
j = i + 1;
while (j < len)
{
if (base[i] == base[j])
return (0);
j++;
}
i++;
}
return (len);
}
void ft_putnbr_base(int nbr, char *base)
{
int i;
int len;
int num;
char result[50];
i = 0;
len = ft_len(base);
if (len < 2)
return ;
if (nbr == 0)
write(1, &base[0], 1);
if (nbr < 0)
write(1, "-", 1);
while (nbr != 0)
{
num = nbr % len;
if (num < 0)
num *= (-1);
result[i++] = base[num];
nbr /= len;
}
while (i > 0)
write(1, &result[--i], 1);
}
#include <unistd.h>
int is_space(char c)
{
char *space;
space = " \n\t\v\f\r";
while (*space != '\0')
{
if (c == *space)
return (1);
space++;
}
return (0);
}
int find_base(char *base, char c)
{
int i;
i = 0;
while (base[i] != '\0')
{
if (base[i] == c)
return (i);
i++;
}
return (-1);
}
int sanitized_base(char *base)
{
char *buffer;
int n;
n = 0;
while (*base)
{
if (*base == '+' || *base == '-' || *base == ' ')
return (0);
buffer = base;
while (*buffer++)
{
if (*buffer == *base)
return (0);
}
n++;
base++;
}
return (n);
}
int ft_atoi_base(char *str, char *base)
{
int result;
int sign;
int i;
int len;
result = 0;
sign = 1;
i = 0;
len = 0;
len = sanitized_base(base);
if (len < 2)
return (0);
while (is_space(str[i]))
i++;
while (str[i] == '-' || str[i] == '+')
{
if (str[i] == '-')
sign *= -1;
i++;
}
while (find_base(base, str[i]) != -1)
result = result * len + find_base(base, str[i++]);
return (result * sign);
}