试题编号: 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;
}