-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_substr.c
More file actions
45 lines (42 loc) · 1.73 KB
/
ft_substr.c
File metadata and controls
45 lines (42 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_substr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jowagner <jowagner@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/26 16:59:06 by jowagner #+# #+# */
/* Updated: 2024/12/12 19:50:32 by jowagner ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/**
* @brief Extracts a substring from a given string,
* starting at a specified index and with a given length.
*
* @param s The string from which to extract the substring.
* @param start The index at which the substring starts.
* @param len The maximum length of the substring to extract.
* @return A pointer to the newly allocated substring,
* or NULL if the allocation fails or if the starting index is out of bounds.
*/
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *substr;
size_t i;
if (start >= ft_strlen(s))
return (ft_strdup(""));
if (len > ft_strlen(s) - start)
len = ft_strlen((char *)s) - start;
substr = (char *)malloc(sizeof(char) * (len + 1));
if (substr == NULL)
return (NULL);
i = 0;
while (i < len && s[start + i])
{
substr[i] = s[start + i];
i++;
}
substr[i] = '\0';
return (substr);
}