Allocates (with malloc(3)) and returns a substring
from the string ’s’.
The substring begins at index ’start’ and is of
maximum size ’len’.
s
에서 start
번째부터 len
길이 만큼char *ft_substr(char const *s, unsigned int start, size_t len);
s
: The string from which to create the substring.start
: The start index of the substring in the stringlen
: The maximum length of the substring.The substring
. NULL
if the allocation fails.#include "libft.h"
char* ft_substr(char const* s, unsigned int start, size_t len)
{
size_t i;
size_t j;
char* sub;
i = 0;
j = 0;
if (!s)
return (NULL);
if (!(sub = (char*)malloc(sizeof(char) * (len + 1))))
return (NULL);
while (s[i])
{
if (i >= start && j < len)
{
sub[j] = s[i];
j++;
}
i++;
}
sub[j] = '\0';
return (sub);
}
int main()
{
char* str;
str = ft_substr("Hello, 42Seoul!", 7, 2);
printf("%s\n", str);
return 0;
}