版权声明: https://blog.csdn.net/leelitian3/article/details/82193968
写在前面
CCF第三题,一道相对简单的字符串模拟题
思路
每次先读取一行line,先把“强调”和“超链接”处理完毕,然后分3种情况处理:
1.若line[0]为‘#’,说明是标题
2.若line[0]为“*”,说明是列表,反复读取并处理直到空行
3.说明是普通的段落,反复读取并处理直到空行
测试数据
C++代码
#include <iostream>
#include <iomanip>
#include <cstring>
#include <sstream>
using namespace std;
void deal_emphasis(string& a)
{
int cnt = 0;
size_t p;
while((p = a.find("_")) != string::npos)
{
++cnt;
if(cnt&1) a.replace(p,1,"<em>");
else a.replace(p,1,"</em>");
}
}
bool deal_url(string& a)
{
int s1,s2,c1,c2;
s1=s2=c1=c2=-1;
for(size_t i=0; i<a.size(); ++i)
{
if(a[i]=='[') s1 = i;
else if(a[i]==']') s2 = i;
else if(a[i]=='(') c1 = i;
else if(a[i]==')') c2 = i;
}
if(s1!=-1 && s2!=-1 && c1!=-1 && c2!=-1 && c1==s2+1)
{
string test(a.begin()+s1+1,a.begin()+s2);
string link(a.begin()+c1+1,a.begin()+c2);
string res = "<a href=\"" + link + "\">" + test + "</a>";
a.replace(s1,c2-s1+1,res);
return 1;
}
return 0;
}
void erase_blank(string& a)
{
for(size_t i=0; i<a.length();)
{
if(a[i] == ' ') a.erase(i,1);
else break;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string tmp, t1,t2;
stringstream ss;
size_t i;
while(getline(cin, tmp))
{
if(tmp.empty()) continue;
ss.clear();
deal_emphasis(tmp);
while(deal_url(tmp));
if(tmp[0] == '#')
{
ss<<tmp;
ss>>t1;
getline(ss,t2);
cout<<"<h"<<t1.length()<<">";
erase_blank(t2);
cout<<t2<<"</h"<<t1.length()<<">\n";
//<h1>Heading</h1>
}
else if(tmp[0] == '*')
{
tmp[0] = ' ';
erase_blank(tmp);
cout<<"<ul>\n"<<"<li>"<<tmp<<"</li>\n";
while(getline(cin, tmp) && !tmp.empty())
{
deal_emphasis(tmp);
while(deal_url(tmp));
tmp[0] = ' ';
erase_blank(tmp);
cout<<"<li>"<<tmp<<"</li>\n";
}
cout<<"</ul>\n";
}
else
{
cout<<"<p>"<<tmp;
while(getline(cin, tmp) && !tmp.empty())
{
deal_emphasis(tmp);
while(deal_url(tmp));
cout<<"\n"<<tmp;
}
cout<<"</p>\n";
}
}
return 0;
}
/*
# heading
## sub-heading
paragraphs are separated
by a blank line.
test _italic_.
bullet list:
* apple
* orange
* pear
[link](http://www.baidu.com).
_[link](http://www.baidu.com)_
*/