ft_substr

one·2021년 1월 21일
0

✅substr

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길이 만큼

💾Prototype

char *ft_substr(char const *s, unsigned int start, size_t len);

💻Parameters

  • s : The string from which to create the substring.
  • start : The start index of the substring in the string
    ’s’.
  • len : The maximum length of the substring.

💻Return value

  • The substring. NULL if the allocation fails.

💾Code

#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);
}

💾Example

int main()
{
	char* str;

	str = ft_substr("Hello, 42Seoul!", 7, 2);
	printf("%s\n", str);

	return 0;
}

profile
늘 호기심을 갖고, 새로운 것에 도전할 것.

0개의 댓글