Do You Coding?
[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'์ด ๋ค์ด๊ฐ๋ฉฐ ๋ง๋ฌด๋ฆฌํ๊ณ ,
๋ฐํํด์ฃผ๋ฉด ์ฐ๋ฆฌ๊ฐ ์ํ๋ '๋ฌธ์์ด ์๋ฅด๊ธฐ'์ ๊ฒฐ๊ณผ๊ฐ ๋์ถ๋๋ค.
'CS & Engineering > 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 |