- 思路:中规中矩的解法,依次判断罢了。
- 坑:在标题和无序列表中会出现空格(如# aaa bbb ccc,* a bc),如果仅仅用字符串流获取会导致结果出错。因此写了一个gettext函数。
#include<iostream>
#include<string>
#include<algorithm>
#include<sstream>
using namespace std;
//标题和无序列表中文本可能含有空格,gettext即获得“去除#*号和一个或多个空格”剩下的文本
string gettext(string line) {
string mark,temp1,temp2,ans;
istringstream ss(line);
ss >> mark>>temp1;
getline(ss, temp2);
ans = temp1 + temp2;
return ans;
}
string changeline(string line) {//改变每行的强调和超链接
int cnt = 1;//改强调
int pos0 = line.find("_");
while(pos0!=-1) {
if(cnt%2==1) {
line.replace(pos0, string("_").length(),"<em>");
cnt++;
}
else if(cnt%2==0) {
line.replace(pos0, string("_").length(), "</em>");
cnt++;
}
pos0 = line.find("_");
}
int pos1 = line.find("[");//改超链接
while (pos1 != line.npos) {
int pos2 = line.find("]");
int pos3 = line.find("(");
int pos4 = line.find(")");
string text, link, oldline, newline;
text = line.substr(pos1+1, pos2 - pos1-1);
link = line.substr(pos3+1, pos4 - pos3-1);
oldline = text + link + "[]()";
newline = "<a href=\"" + link + "\">"+text + "</a>";
line.replace(pos1,oldline.length(),newline);
pos1 = line.find("[");
}
return line;
}
int main() {
bool para = false,nolist=false,newline=true;//记录是否是一段内容/无序列表的结尾、记录是否是新一段的开头
string line;
string ans;
int cnt = 0;//判断是否是第一行数据
while (getline(cin, line)) {
line=changeline(line);//首先改变每一行的强调和超链接
int num1 = line.find("*");//找*,有则=-1,无则=0
int num2 =count(line.begin(),line.end(),'#');//找#,有则=个数,无则=0
if (line == "") {//如果是空行
newline = true;
if (para) {
ans += "</p>";
para = false;
}
if (nolist) {
ans += "\n</ul>";
nolist = false;
}
continue;//跳过下面判断和+“\n”,即为删除空行
}
if (!num1) {//如果*存在
nolist = true;
string text1 = gettext(line);
if (newline) {
line= "<ul>\n<li>" + text1 + "</li>";
newline = false;
}
else {
line= "<li>"+text1 + "</li>";
}
}
if (num2) {//如果#存在
string text2 = gettext(line);
line= "<h" + to_string(num2) + ">" + text2 + "</h" + to_string(num2) + ">";
}
else if(newline) {//如果不存在#和*,但又是新行
para = true;
newline=false;
line="<p>" + line;
}
if (cnt == 1) {//如果不是第一行,则先换行,再加上由前面的if语句修改过的line
ans += "\n" + line;
}
if (cnt == 0) {//如果是第一行,则不换行
ans += line;
cnt++;
}
}//在结尾处再次判断是否应该添加(同空行处)
if (para) {
ans += "</p>";
}
if (nolist) {
ans += "\n</ul>";
}
cout << ans;
return 0;
}
【20200430】