机试真题 HTML字符串匹配的问题

坑挺多的,没有现成的测试用例,不知道包含不包含JS,或者特殊标签的问题;

所以一切按照规格HTML来进行;

例如百度的简单网页:https://mbd.baidu.com/newspage/data/landingsuper?context=%7B%22nid%22%3A%22news_9354867863558310355%22%7D&n_type=0&p_from=1

 

其实总的来说就是字符串匹配问题,寻找标签: <img src=" ">,只需要匹配前半部分,找到=后的索引,直接string substr即可;

 

个人觉得还用不到KMP那么麻烦的东西;

 

所以只需要找到src索引部分保存即可;

 

涉及内容:

1.IO问题;

2.string基本操作;

3.读入的时候采用拼接一次性保存;

 

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;

string path = "C:\\Users\\Reality\\Desktop\\random\\test.html";
string as = "";
vector<string>result;

int fcharge(int index) {
    string ptn = "<img src=";
    int rs;
    for (int i = index,j=0;j<ptn.size()&&i<as.size(); i++,j++) {
        if (ptn[j] != as[i]) {
            return -1;
        }
        else {
            rs = i;
        }
    }
    return rs + 1;
}

int scharge(int index) {
    for (int i = index+1; i < as.size(); i++) {
        if(as[i]=='"')
            return i;
    }
    //错误情况
    return -1;
}

void fun() {
    int index = 0;
    for (; index < as.size(); index++) {
        if (as[index] == '<') {
            int fr = fcharge(index);
            if (fr != -1) {
                int sr = scharge(fr);
                string s = as.substr(fr + 1, sr - fr - 1);
                result.push_back(s);
            }
        }
    }
}

int main() {
    fstream fin;
    fin.open(path, ios::in);
    string s;
    while (getline(fin, s)) {
        as += s;
    }
    fun();
    for (auto ele : result)
        cout << ele << endl;
    fin.close();
}

 

posted @ 2020-04-09 10:09  暮云林凌  阅读(260)  评论(0)    收藏  举报