HDU 4782 Beautiful Soup 模拟

题意:给出你HTML的格式标记,让你按照层次,把对应的格式输出出来。

思路:因为整个层次可以看做是个递归的,我们就可以递归来写。

           其中需要非常注意的是,会有个空括号,他是不会让层次加1的。

           同时,在C++中,cin会自动的跳过空格字符,如果想一个字符一个字符的读,要用cin.get().

          整体结构还是挺清晰的,看代码吧。

代码如下:

#include <string>
#include <iostream>
#include <cctype>
#include <cstdio>

using namespace std;

void space(int d)
{
    for(int i = 0; i < d; ++i)
        cout<<' ';
}

void gettag(string& tag)
{
    tag.clear();
    char ch;
    ch = cin.get();
    while(ch != '>'){
        tag += ch;
        ch = cin.get();
    }
}
void word()
{
    char ch;
    ch = cin.get();
    bool sig = true;
    while(ch != '<'){
        if(sig) sig = false;
        else cout<<' ';
        do{
            cout<<ch;
            ch = cin.get();
        }while(!isspace(ch) && ch != '<');
        if(isspace(ch)){
            while(isspace(ch))
                ch = cin.get();
        }
    }
    cin.putback(ch);
    cout<<'\n';
}

void solve(int d,string tag,bool sig)
{
    char ch;
    string tag2;
    if(sig){
        space(d);
        if(tag.size() == 0)
            word();//输出单词
        else
            cout<<"<"<<tag<<">\n";//输出空括号
    }
    else{
        space(d); cout<<"<"<<tag<<">\n";
        while(true){
            cin>>ch;
            if(ch != '<'){
                cin.putback(ch);
                solve(d+1,"",true);
            }
            else{
                gettag(tag2);
                if(tag2[tag2.size()-1] == '/')
                    solve(d+1,tag2,true);//为空括号
                else if(tag2[0] == '/')//为结束括号
                    break;
                else//否则为开始括号
                    solve(d+1,tag2,false);
            }
        }
        //输出结束括号,要把class内容删掉
        int pos = tag.find(' ');
        if(pos != -1)
            tag.erase(pos);
        space(d);cout<<"</"<<tag<<">\n";
    }
}

int main(void)
{
    //freopen("input.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    ios::sync_with_stdio(false);
    int T;
    cin>>T;
    char ch;
    for(int i = 1; i <= T; ++i){
        cout<<"Case #"<<i<<":\n";
        string tag;
        cin>>ch;
        gettag(tag);
        solve(0,tag,false);
        //cout<<tag<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值