【CCFCSP】201703-3 Markdown

本文介绍了一个简单的Markdown到HTML的转换程序,通过该程序可以将Markdown格式的文本转换为标准的HTML格式。转换过程中考虑了段落、无序列表、标题、强调文本和超链接等多种Markdown元素,并详细展示了如何使用C++实现这一转换。

试题编号: 201703-3
试题名称: Markdown
时间限制: 1.0s
内存限制: 256.0MB

比较简单的字符串处理问题,用if-else语句对每种情况做不同的操作。
Markdown的行内语法可以在最先进行转换,然后用转换后的字符串替换读入串,比较简单。
还要注意读入段落和无序列表时结束标记的输出,具体可以以下代码的处理。

int main() {
    string s;
    bool para = 0, ul = 0;//para = 1表示正在读取段落,ul = 1表示正在读取无序列表
    int p1, p2, p3, p4;
    while (getline(cin, s)) {
        //首先把"强调"转换成相应格式
        while ((p1 = s.find("_")) != -1) {
            string tmp;
            s[p1] = 0;
            tmp.append(s, 0, p1);
            tmp += "<em>";
            p2 = s.find("_");
            tmp.append(s, p1 + 1, p2 - p1 - 1);
            tmp += "</em>";
            tmp.append(s, p2 + 1, s.length() - p2 - 1);
            s = tmp;
        }
        //同样的把"链接"转换成相应格式
        while ((p1 = s.find('[')) != -1) {
            p2 = s.find(']');
            p3 = s.find('(');
            p4 = s.find(')');
            string tmp;
            tmp.append(s, 0, p1);
            tmp += "<a href=\"";
            tmp.append(s, p3 + 1, p4 - p3 - 1);
            tmp += "\">";
            tmp.append(s, p1 + 1, p2 - p1 - 1);
            tmp += "</a>";
            tmp.append(s, p4 + 1, s.length() - p4 - 1);
            s = tmp;
        }
        //进入下一个区块前,如果上一个区块是段落,输出</p>
        //如果是无序列表,输出</ul>
        if (s.length() == 0) {
            if (para) {
                cout << "</p>" << endl;
                para = 0;
            }
            if (ul) {
                cout << "</ul>" << endl;
                ul = 0;
            }
            continue;
        }
        else if (s[0] == '#') {
            int num = 0;//保存#的数量
            while (s[num] == '#') num++;
            cout << "<h" << num << ">";
            int p = num + 1;
            while (s[p] == ' ') p++;//跳过空格
            for (int i = p; i < s.length(); i++)
                cout << s[i];
            cout << "</h" << num << ">" << endl;
        }
        else if (s[0] == '*' || ul) {
            if (!ul) {
                cout << "<ul>" << endl;
                ul = 1;
            }
            cout << "<li>";
            int p = 1;
            while (s[p] == ' ') p++;//跳过空格
            for (int i = p; i < s.length(); i++)
                cout << s[i];
            cout << "</li>" << endl;
        }
        else {
            //因为段落的结束符在最后一行的末尾,所以输出段落时做一点处理
            if (para) cout << endl;
            if (!para) {
                cout << "<p>";
                para = 1;
            }
            cout << s;
        }
    }
    //要考虑最后一行是段落或者无序列表的情况
    if (para) {
        cout << "</p>" << endl;
    }
    if (ul) {
        cout << "</ul>" << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值