问题描述:
大致思路:
处理字符串的问题,可以梳理成以下表格帮助梳理思路:如何识别类型+如何输出该类型
根据输入逐行判断:
- 根据行首判断区块的类型,进行相应的处理
- 在对行内处理时,依据行内结构的特殊字符进行识别并进行相应处理。
OK~上代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
void get_link(string str){
string text="",link="";
int i;
for(i=1;str[i]!=']';i++){//处理text
char c=str[i];
if(c=='_'){
text+="<em>";
i++;
while(str[i]!='_') text+=str[i++];
text+="</em>";
}
else text+=c;
}
for(i=i+2;str[i]!=')';i++){//处理link
char c=str[i];
if(c=='_'){
link+="<em>";
i++;
while(str[i]!='_') link+=str[i++];
link+="</em>";
}
else link+=c;
}
cout<<"<a href="<<'\"'<<link<<'\"'<<'>'<<text<<"</a>";
}
void get_em(string str){
cout<<"<em>";
for(int i=1;i<str.size()-1;i++){
if(str[i]=='['){
int j=i+1;
while(str[j]!=')')j++;
get_link(str.substr(i,j-i+1));
i=j;
}
else cout<<str[i];
}
cout<<"</em>";
}
void getInLine(string str){//处理行内
for(int i=0;i<str.size();i++){
if(str[i]=='_'){
int j=i+1;
while(str[j]!='_') j++;
get_em(str.substr(i,j-i+1));
i=j;
}
else if(str[i]=='['){
int j=i+1;
while(str[j]!=')')j++;
get_link(str.substr(i,j-i+1));
i=j;
}
else cout<<str[i];
}
}
int main(){
string line;
int pre=0;//上一行的类型:空行0,标题1,列表2,段落3
while(getline(cin,line)){
if(!line.size()){
if(pre==2) cout<<"</ul>"<<endl;
else if(pre==3) cout<<"</p>"<<endl;
pre=0;
}
else if(line[0]=='#'){//标题
int cnt=0,i=0;
while(line[i]=='#'||line[i]==' '){
if(line[i]=='#') cnt++;
i++;
}
if(cnt<=6) cout<<"<h"<<cnt<<">";
else cout<<"<h6>";
getInLine(line.substr(i));
if(cnt<=6) cout<<"</h"<<cnt<<">"<<endl;
else cout<<"</h6>"<<endl;
pre=1;
}
else if(line[0]=='*'){//无序列表
int i=0;
if(pre==0) cout<<"<ul>"<<endl;
while(line[i]=='*'||line[i]==' ') i++;
cout<<"<li>";
getInLine(line.substr(i));
cout<<"</li>"<<endl;
pre=2;
}
else{//段落
if(pre==0) cout<<"<p>";
else if(pre==3) cout<<endl;
getInLine(line);
pre=3;
}
}
//最后一个区块末尾部分记得处理
if(pre==2) cout<<"</ul>"<<endl;
else if(pre==3) cout<<"</p>"<<endl;
return 0;
}
一些小Tips:
- 大模拟题除了需要仔细思考如何存储快速简单的问题,还重在理解题意以及细节的处理,保持好心态,要对自己有信心!(ง •_•)ง
- 按行读入数据,直至输入结束的读取输入的方法:
#include <iostream>
#include <cstring>
using namespace std;
int main{
string line;
while(getline(cin,line)){
...
}
}
- 使用双指针算法时,要注意对当前识别对象识别完成后,指针位置的移动:
for(int i=0;i<n;i++){
int j=i;
while(j<n&&判断条件) j++;
//..对i~j之间的字符串进行相应的处理操作
i=j;//!!!一定要记得
}
- 模拟题不能ac时自己多设计几组测试数据测试一下,不要怕麻烦~