2022년 2월 12일 토요일

C++ 문자열 분리 방법 2강

 지난번 강의 에 이어 오늘 포스트할 내용은 기본 분리에 다시 상세 분리를 하여

만들어 놓은 구조체에 담아 저장후 출력하는것으로 이어 가겠습니다.

지난번 강의는 아래 링크로 확인해 주세요.

C++ 문자열 분리 방법 1강

소스를 보기 전에 처리 하는 방법을 설명 드리고 시작 하겠습니다.

문자열을 파싱하여 담을 구조체를 설계합니다. 저는 아래와 같이 구조체로 설계 했습니다.

typedef struct _BlogPostInfo
{
    string sTitle;
    string sID;
    string sDate;
}BLOGPOSTITEM;

그리고 개별 아이템을 분리하여 구조체에 담는 처리를 하기 위해서 별도 함수를 작성하여 활용 했습니다.

함수 원형은 아래와 같으며 나머지는 동작한는 소스를 확인한후 설명을 이어가도록 하겠습니다.

void doParseItem(string& sItem, BLOGPOSTITEM* pItem)

#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>

using namespace std;

typedef struct _BlogPostInfo
{
    string sTitle;
    string sID;
    string sDate;
}BLOGPOSTITEM;

void doParseItem(string& sItem, BLOGPOSTITEM* pItem)
{
    string sSepChar = "=", sKey, sValue;
    size_t nIndex = sItem.find(sSepChar);

    if (nIndex != string::npos)
    {
        sKey = sItem.substr(0, nIndex);
        sValue = sItem.substr(nIndex+sSepChar.size(), sItem.size()-(nIndex+sSepChar.size()));

        if(sKey == "Title")
            pItem->sTitle = sValue;
        
        if(sKey == "Writer")
            pItem->sID = sValue;

        if(sKey == "PostDate")
            pItem->sDate = sValue;
    }
}

int main()
{
    string sOrgSrc = "Title=Blog@Writer=Berdo@PostDate=20220120";
    string sSepChar = "@", sTemp, sParse = sOrgSrc;

    BLOGPOSTITEM postItem;
    memset(&postItem, 0x00, sizeof(BLOGPOSTITEM));

    // string find 를 이용하여 아이템 기본 분리.
    size_t nIndex = sParse.find(sSepChar);

    while (nIndex != string::npos)
    {
        string sItem = sParse.substr(0, nIndex);
        doParseItem(sItem, &postItem);
        sParse = sParse.substr(nIndex+sSepChar.size(), sParse.size()-(nIndex+sSepChar.size()));
        nIndex = sParse.find(sSepChar);
    }

    //마지막항목.
    //cout << "[Item:" << sParse << "]" << endl;
    doParseItem(sParse, &postItem);

    
    cout << "==============================" << endl;
    cout << "BlogItem Title: " <<  postItem.sTitle << endl;
    cout << "BlogItem Writer: " << postItem.sID << endl;
    cout << "BlogItem Date: " << postItem.sDate << endl;
    cout << "==============================" << endl;

    return 1;
}

소스를 리딩하는것은 함수먼저 보는것이 아니라 시작되는 프로그램부터 보면서 안쪽으로 분석 하시는 방법으로 하는것을 추천 드립니다.

위 소스의 시작은 main 함수 입니다.

기존에 구현한 함수와는 별차이가 없고 추가된것은 구조체 선언한 변수 postItem 가 들어가 있습니다.

'@' 문자열로 파싱한 아이템을 넘겨서 postItem 에 개별 담기를 하기 위해서 doParseItem 함수가 호출된것을 볼수 있습니다.

doParseItem 함수는 'Key=Value' 형태로 넘어오는 문자열을 파싱하여 구조체에 원하는 항목으로 집어넣는 과정입니다.

함수 시작과 함께 for 문과 마지막항목 분리로 Key와 Value 값을 추출한후

마지막에 Key 값에 따라 구조체 항목에 집어 넣는 과정으로 분류 됩니다.

일련의 과정이 끝나고 나면 마지막에 구조체 항목을 상세히 출력하여 온전하게 분리된 문자열 데이터를 보실수 있습니다.

그럼 이만 ^^

댓글 없음: