HTML 파싱 22859

PublicMinsu·2023년 6월 19일

문제


생략

접근 방법

생각보다 형식에 제한을 많이 둔 상태로 주기에 find를 활용해도 문제없다.
main은 쓸모없기에 초반에 삭제해 주고 div 단위로 나누어준 뒤 그것을 또 p단위로 나누어주면 된다.
p에서는 내부에 태그가 필요 없기에 <와 >사이에 있는 값을 모두 지워준다고 생각하면 된다.

코드

#include <iostream>
#include <string>
using namespace std;

string origin;
int titleStart, titleEnd, pStart, pEnd, nextStart;
string makeP(string p)
{
    string temp = "";
    bool spaceFlag = true;
    for (int i = 0; i < p.length(); ++i)
    {
        if (p[i] == '<')
        {
            i = p.find('>', i);
            continue;
        }

        if (p[i] != ' ') // 공백이 아니면 더해준다
        {
            spaceFlag = false;
            temp += p[i];
        }
        else
        {
            if (spaceFlag)
                continue;
            spaceFlag = true;
            temp += p[i];
        }
    }
    return temp;
}
int main()
{
    ios::sync_with_stdio(0), cin.tie(0);
    getline(cin, origin);
    origin = origin.substr(6, origin.length() - 13); // main 제거
    while (true)
    {
        titleStart = 0;
        titleStart = origin.find("\"", titleStart);
        ++titleStart;
        titleEnd = origin.find("\"", titleStart);
        cout << "title : " << origin.substr(titleStart, titleEnd - titleStart) << "\n";
        origin = origin.substr(titleEnd);
        nextStart = origin.find("title=", titleEnd);
        pEnd = 0;
        while (true)
        {
            pStart = origin.find("<p>", pEnd);
            if (pStart == -1 || (nextStart != -1 && pStart > nextStart))
                break;
            pStart += 3;
            pEnd = origin.find("</p>", pStart);
            cout << makeP(origin.substr(pStart, pEnd - pStart)) << "\n";
        }
        if (nextStart == -1)
            break;
        origin = origin.substr(nextStart);
    }
    return 0;
}

풀이

div 단위에서는 제목을 빼내면 되고 이후에는 p 단위로 나누어서 내용을 빼내면 된다.
'<div'로 find하면 문제가 있는데 웃기게도 div 태그 사이에 div로 시작하는 경우가 존재할 수 있기 때문이다.
질문 게시판에서 찾다가 알게 됐다.
'title : '로 바꾸어서 해결하였다.

profile
연락 : publicminsu@naver.com

0개의 댓글