C/Code snippet
[C] 문자열 파싱 (strtok없이), strcpy, strdup, strlen
2022. 7. 10. 19:29반응형
소스코드: 문자열 파싱
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <strings.h>
int main(void)
{
int i = 0, j = 0, n = 0;
char* words = "This is a sentence";
char word[20];
char* s[4];
while (words[i] != '\0')
{
// ' ' is the separator to split words
if (words[i] == ' ')
{
word[j] = '\0';
s[n] = malloc(sizeof(word));
strcpy(s[n], word);
j = 0;
n++;
memset(word, 0, sizeof(word));
}
else
{
word[j++] = words[i];
}
i++;
}
// The last word isn't delimited by a ' ', so
// we copy it separately (you could also make it point
// to word, which now holds only the last word
s[n] = malloc(sizeof(word));
strcpy(s[n], word);
// Print the result through the console
int z = 0;
for (z = 0; z <= n; z++)
{
printf("%s\n", s[z]);
}
}
출력화면
This is a sentence |
참고자료/출처
소스코드: strlen, strcpy 성질
#include<stdlib.h>
#include<stdio.h>
int main(void)
{
char str[] = {'1', '2', '3', '\0', '4', '5', '6', '\0', '7', '8', '9', '\0'};
printf("sizeof: %d\n", sizeof(str));
// Check 1
printf("strlen(..): %d\n", strlen(str));
printf("strlen(..): %d, starts wieh 5 index\n", strlen(str + 5));
char dst[100] = {0,};
strcpy(dst, str);
// Check 2
printf("strcpy %s\n", dst);
return 0;
}
출력
sizeof: 12 strlen(..): 3 strlen(..): 2, starts wieh 5 index strcpy 123 |
설명
strlen은 널문자까지 길이로써 계산한다.
strcpy는 널문자까지의 문자열을 src에 복사를 한다.
소스코드: strdup
#include<stdlib.h>
#include<stdio.h>
int main(void)
{
char str[] = {'1', '2', '3', '\0', '4', '5', '6', '\0', '7', '8', '9', '\0'};
char *dup;
printf("strlen(..): %d\n", strlen(str));
dup = strdup(str);
printf("dup test: %s\n", dup);
return 0;
}
출력
strlen(..): 3
dup test: 123
설명
strdup도 널문자를 기준으로, 새로운 문자열을 만든다.
반응형
'C > Code snippet' 카테고리의 다른 글
[C] strlen의 인자로 char* 자료형을 넣었을 때 결과 확인 코드 (0) | 2023.01.27 |
---|---|
[C] 예제코드: 파일읽기, 삭제 (0) | 2023.01.15 |
[C] exec - execl 예제, c언어 내부에서 ls 같은 시스템 명령어 실행하기 (0) | 2022.06.03 |
[C/코드해석] pop_string (0) | 2022.05.26 |
[C][Linux] realloc, malloc 그리고 malloc 사이즈 구하기 (0) | 2022.05.22 |