CCF_2017_03_3_Markdown

解题思路,按照题中说的区块,分块处理,觉得更符合思考习惯。然后对区块中的强调和超级链接进行处理。
个人觉得,解题的关键,首先是,对测试样例的设计,再者,就是对题意完整的把握(例如,链接,强调中不会出现换行)。
自己设计的测试数据如下。
区块内部:
1、强调中加入1链接;
2、强调中加入多个连接;
3、链接的文本text中加入1强调;
4、链接中文本加入多个个强调;
5、链接+强调中加入链接;
6、强调中加入链接+链接;(5,6是根据程序内部逻辑结构设计)
然后是将区块类型和区块内部类型的组合。
测试数据:(测试通过文本读入方式进行)

当然,对于一些细节还需要别的一些数据进行检测,或者,根据程序内部逻辑适当删减一些用例。
通过的代码如下。

#include<iostream>
#include<string>
using namespace std;
int getType(string&s) {//获取区块的类型。
	if (s.empty()) {//空行
		return -1;
	}
	if (s[0] == '#') {//标题;
		int i = 1;
		int len = s.length();
		while (i<len&&s[i++] == '#');
		return i-1;
	}
	else if (s[0] == '*') {//无序列表
		return 7;
	}
	else {//段落;
		return 0;
	}
}
void dealInText(string&s,int i) {
	int len = s.length();
	string text;
	string link;
	int k = 0;
	while (s[i] == ' ') {
		++i;
	}
	while(i < len){
		if (s[i] == '_') {//处理__;
			std::cout << "<em>";
			++i;
			while (s[i] != '_'&&i<len) {
				if (s[i] == '[') {//处理__中的链接;
					++i;
					while (s[i] != ']') {
						text += s[i++];
					}
					i += 2;
					while (s[i] != ')') {
						link += s[i++];
					}
					++i;
					std::cout << "<a href=" << '"' << link<< '"' << ">" << text << "</a>";
					text.clear();
					link.clear();
				}
				else {
					std::cout << s[i++];
				}
			}
			++i;
			std::cout << "</em>";
		}
		else if (s[i] == '[') {//处理链接
			++i;
			while (s[i] != ']') {
				if (s[i] == '_') {//对链接文本进行处理中的__;
					++i;
					text += "<em>";
					while (s[i] != '_') {
						text += s[i++];
					}
					text += "</em>";
					++i;
				}
				else {
					text += s[i++];
				}
			}
			i += 2;
			while (s[i] != ')') {
					link += s[i++];
			}
			++i;
			std::cout << "<a href=" << '"' << link << '"' << ">" << text << "</a>";
			text.clear();
			link.clear();
		}
		else {
			std::cout << s[i++];
		}
	}

}
void dealText() {
	string line;
	while (getline(cin, line)) {
		int type = getType(line);
		if (type != -1) {
			if (type < 7 && type >= 1) {//处理标题;
				std::cout << "<h" << type << ">";
				dealInText(line, type);
				std::cout << "</h" << type << ">" << endl;

			}
			else if (type == 7) {//处理无序列表;
				std::cout << "<ul>" << endl;
				std::cout << "<li>";
				dealInText(line, 1);
				std::cout << "</li>" << endl;
				while (getline(cin, line)) {
					if (getType(line) == -1)
						break;
					std::cout << "<li>";
					dealInText(line, 1);
					std::cout << "</li>" << endl;
				}
				std::cout << "</ul>" << endl;
			}
			else if (type == 0) {//处理段落块;
				std::cout << "<p>";
				dealInText(line, 0);
				while (getline(cin, line)) {
					if (getType(line) == -1) {
						break;
					}
					std::cout << endl;
					dealInText(line, 0);
				}
				std::cout << "</p>" << endl;
			}
		}
	}
}
int main(){
    dealText();
    return 0;
}
如有不当,欢迎指正 :)
原文地址:https://www.cnblogs.com/lif323/p/7456907.html