반응형

 

소스코드: 문자열 파싱

#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

 

참고자료/출처

https://cs50.stackexchange.com/questions/21851/split-a-sentence-ito-an-array-of-words-without-using-strtok

 


 

소스코드: 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도 널문자를 기준으로, 새로운 문자열을 만든다.

 

 

반응형