Do You Coding?

[library] substr ๊ตฌํ˜„ํ•˜๊ธฐ ๋ณธ๋ฌธ

CS & Engineering/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'์ด ๋“ค์–ด๊ฐ€๋ฉฐ ๋งˆ๋ฌด๋ฆฌํ•˜๊ณ ,

๋ฐ˜ํ™˜ํ•ด์ฃผ๋ฉด ์šฐ๋ฆฌ๊ฐ€ ์›ํ•˜๋Š” '๋ฌธ์ž์—ด ์ž๋ฅด๊ธฐ'์˜ ๊ฒฐ๊ณผ๊ฐ€ ๋„์ถœ๋œ๋‹ค.