본문 바로가기

프로그래밍/C

[library] substr 구현하기

📌 매뉴얼 (in subject)

더보기

Function name

     do_substr

 

Prototype

     char *do_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.

: s: 잘린 부분 문자열을 생성할 문자열입니다.
start: 문자열 's'에 있는 부분 문자열의 시작 인덱스입니다.
len: 서브스트링의 최대 길이입니다.

 

Return value

     The substring. NULL if the allocation fails.

: 서브스트링(잘린 문자열). 할당에 실패하면 NULL입니다.

 

External functs

     malloc

 

Description

    Allocates (with malloc(3)) and returns a substring from the string ’s’. The substring begins at index ’start’ and

    is of maximum size ’len’.

: malloc을 사용하여 할당하고 문자열 's'에서 잘린 문자열을 반환합니다.

잘린 문자열은 인덱스 'start'에서 시작하고 최대 크기 'len'입니다.

 

📌 작성 코드

char	*do_substr(char const *s, unsigned int start, size_t len)
{
	char		*str;
	size_t		i;

	if (s == NULL)
		return (NULL);
	if (do_strlen(s) < start)
		len = 0;
	str = (char *)malloc(sizeof(char) * (len + 1));
	if (str == NULL)
		return (NULL);
	i = 0;
	while (i < len && s[start] != '\0')
	{
		str[i] = s[start];
		i ++;
		start ++;
	}
	str[i] = '\0';
	return (str);
}

 

📌 코드 리뷰

substr 함수는 sub string, 즉 잘린 문자열을 반환해주는 함수로 쓰인다.

 

우선 매개변수를 살펴보면, s 문자열을 가져와 start 인덱스부터 len 만큼 잘라주는데,

이 len이 기존 s의 범위를 넘어서면 끝 위치까지만 잘라주면 되기에 len을 '잘라질 최대 크기'로 보면 되겠다.

 

기존 문자열에 영향이 가지 않도록, char const *s로 매개변수를 받아오기에, s의 값만 가져와

새 문자열에 넣어주는 방식으로 만들면 되겠다고 생각했고,

str 이라는 새 문자 배열을 생성해주고 malloc을 통해 len + 1 만큼 (최대 길이 + NULL 자리) 동적할당해줬다.

 

예외적으로, s의 길이가 start보다 작으면, 자를 문자열의 시작점이 이미 벗어난 상태이므로,

len을 0으로 하여 자르는 과정을 하지 않게 해준다. (이후에 str[0]에 '\0'이 들어가며 반환은 NULL이 된다.)

 

이제 문자열을 자른 만큼 반환하기 위해, start부터 시작된 s를 len만큼 또는 s가 '\0' (문자열 끝)을 만날때 까지

str에 s의 start 인덱스부터 차례차례 넣어준다. 그렇게 마지막으로 str 마지막 인덱스에 '\0'이 들어가며 마무리하고,

반환해주면 우리가 원하는 '문자열 자르기'의 결과가 도출된다.

'프로그래밍 > C' 카테고리의 다른 글

[library] strtrim 구현하기  (0) 2024.06.27
[library] strjoin 구현하기  (0) 2024.06.26
[function] waitpid 함수 알아보기  (2) 2024.06.13
[function] wait 함수 알아보기  (0) 2024.06.09
[function] unlink 함수 알아보기  (2) 2024.06.07
Recent Posts
Popular Posts
Recent Comments