201703-3 Markdown
思路
本题要求比较繁琐,但实现的思路不复杂。三种区块的处理方式很类似,其中内容的处理是一样的,可专门写一个change函数。对于区块的开头结尾,可以设置一个flag标志。详见代码。
梦想有一天我也会正则表达式=_=
AC代码如下
#include<string>
#include<iostream>
#include<vector>
using namespace std;
void change(string &str){//处理每一行的内容
int s=0;
while(1){//处理'_Text_'
s=str.find("_");
if(s==string::npos) break;
int t=str.find("_",s+1);
str.replace(t,1,"</em>");
str.replace(s,1,"<em>");
}
while(1){//处理超链接
s=str.find("[");
if(s==string::npos) break;
int t=str.find("]",s+1);
int ed=str.find(")",t+2);
string text,link;
text=str.substr(s+1,t-s-1);
link=str.substr(t+2,ed-t-2);
str.replace(s,ed-s+1,"<a href=\""+link+"\">"+text+"</a>");
}
}
int main(){
vector<string> html;
string line;
int flag=0;
while(getline(cin,line)){
if(line.size()==0){//空行,考虑给上一区块收尾
if(flag==1) html.push_back("</ul>");
else if(flag==2) html[html.size()-1]+="</p>";
flag=0;
continue;
}
else if(line[0]=='#'){//标题
int d=0;
while(line[d]=='#') d++;//标题等级
if(d>6) d=6;
string temp;
//标题头标记
temp="<h";
temp.insert(temp.end(),(char)(d+'0'));//不知道有没有更好的插入方法
temp+=">";
int s=d;
while(line[s]==' ') s++;
string content=line.substr(s,line.size()-s);
change(content);//处理内容
//标题尾标记
temp+=content+"</h";
temp.insert(temp.end(),(char)(d+'0'));
temp+=">";
html.push_back(temp);
}
else if(line[0]=='*'){//无序列表
if(flag==0){//第一行之前加标志
flag=1;
html.push_back("<ul>");
}
int s=1;
while(line[s]==' ') s++;
string temp,content;
content=line.substr(s,line.size()-s);
change(content);//处理内容
temp="<li>"+content+"</li>";
html.push_back(temp);
}
else {//普通段落
string temp,content;
if(flag==0){
flag=2;
temp+="<p>";
}
content=line;
change(content);//处理内容
temp+=content;
html.push_back(temp);
}
}
if(flag==1) html.push_back("</ul>");//最后没有空行了要记得收尾
else if(flag==2) html[html.size()-1]+="</p>";
for(int i=0;i<html.size();i++) cout<<html[i]<<endl;
return 0;
}