CCF201703-3 Markdown
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
标题--1;无序列表--2;段落--3
标题
无序列表:
1.前面一次输入不是列表,那么先追加一个 “<ul>”,然后修改这次输入,前后加上 “<li>”和 “</li>”
2.前面一次输入是列表,直接修改这次输入内容,并删除上一个输入末行的 “</ul>”
3.在最后追加一个 “</ul>”
段落:
首先在输入末尾加上“</p>”
1.前面一次输入不是段落,那么这次输入的段落最前面加上 “<p>”
2.前面一次输入是一个段落,那么这次输入不操作;去掉上一次输入末尾的 “</p>”
强调;简单的替换
超链接:简单的替换
*/
vector<string> result = vector<string>();
enum Tuple{
INIT,TITLE,LIST,PARA,NEWLINE
};
int TYPE = INIT;
int LAST_TYPE = INIT;
string str = "";
void do_title();
void do_list();
void do_para();
void do_emphysis(string&);
void do_link(string&);
int main()
{
while(getline(cin,str)){
if(str=="\0"){
LAST_TYPE = TYPE;
TYPE = NEWLINE;
continue;
}
char ch = str[0];
if(ch=='#'){ LAST_TYPE = TYPE; TYPE = TITLE; do_title(); }
else if(ch=='*'){ LAST_TYPE = TYPE; TYPE = LIST; do_list();}
else{ LAST_TYPE = TYPE; TYPE = PARA; do_para(); }
}
for(int i=0;i<result.size();i++)
cout<<result[i]<<endl;
return 0;
}
void do_link(string& str){
string::size_type pos1,pos2,pos3,pos4;
pos1 = str.find("[");
pos2 = str.find("]");
pos3 = str.find("(");
pos4 = str.find(")");
while(string::npos!=pos1){
string str_a = str.substr(pos1+1,pos2-pos1-1);
string str_b = str.substr(pos3+1,pos4-pos3-1);
string insert_str = "<a href=\"";
insert_str = insert_str + str_b;
insert_str = insert_str + "\">";
insert_str = insert_str + str_a;
insert_str = insert_str + "</a>";
str.replace(pos1,pos4-pos1+1,insert_str);
pos1 = str.find("[");
pos2 = str.find("]");
pos3 = str.find("(");
pos4 = str.find(")");
}
}
void do_emphysis(string& str){
string exc_str1 = "<em>";
string exc_str2 = "</em>";
string find_str = "_";
int find_count = 0;
string::size_type pos;
pos = str.find(find_str);
while(string::npos!=pos){
find_count++;
if(find_count%2==1){
str.replace(pos,find_str.length(),exc_str1);
}else{
str.replace(pos,find_str.length(),exc_str2);
}
pos = str.find(find_str);
}
}
void do_para(){
string tmp = "";
if(LAST_TYPE==PARA){
string &last_para = result.back();
last_para = last_para.substr(0,last_para.size()-4);
tmp = str + "</p>";
}else{
tmp = str;
tmp = string("<p>") + tmp;
tmp = tmp + "</p>";
}
do_emphysis(tmp);
do_link(tmp);
result.push_back(tmp);
}
void do_list(){
int i = 1;
string tmp = "";
for( ;i<str.size();i++){
if(str[i]!=' ') break;
}
str = str.substr(i);
if(LAST_TYPE==LIST){
tmp = string("<li>") + str;
tmp = tmp + "</li>";
string pop_str = result.back();
if(pop_str=="</ul>") result.pop_back();
}else{
result.push_back(string("<ul>"));
tmp = string("<li>") + str;
tmp = tmp + "</li>";
}
do_emphysis(tmp);
do_link(tmp);
result.push_back(tmp);
result.push_back(string("</ul>"));
}
void do_title(){
int star_count = 0;
int i = 0;
for( ;i<str.size()&&str[i]=='#';i++,star_count++);
for( ;i<str.size()&&str[i]==' ';i++);
string tmp = "<h";
char ch = star_count + 48;
tmp = tmp + ch + ">";
tmp = tmp + str.substr(i);
tmp = tmp + "</h" + ch + ">";
do_emphysis(tmp);
do_link(tmp);
result.push_back(tmp);
}
有缘再见