1、提取文件名
std::find_end(str.begin(), str.end(), pattern.begin(), pattern.end())
std::search()
- find函数主要实现的是在容器内查找指定的元素,并且这个元素必须是基本数据类型的。查找成功返回一个指向指定元素的迭代器,查找失败返回end迭代器。
std::find()
- 返回两个迭代器之间的距离,也可以理解为计算两个元素 first 和 last 之间的元素数
std::distance(str.begin(), result)
- substr()截取字符串子序列,第一个参数为开始索引,第二参数是子序列长度
- substring() 截取字符串子序列,第一个参数为开始索引,第二参数是结束索引
str.substr(0, std::distance(str.begin(), result) + 1)
- #include <iostream>
- #include <string>
- # include <algorithm> //注意要包含该头文件
- using namespace std;
- std::string ExtractFileName(std::string path)
- {
- //不带后缀名的文件名
- std::string fileBaseName;
- //文件目录
- std::string str = path;
- //待匹配的子序列
- std::string pattern = "/";
- //查找容器内子序列的最后一次出现的位置,在[str.begin(),str.end ())内搜索由[pattern.begin(), pattern.end())
- //组成的子序列,然后将迭代器返回到其第一个元素,即pattern.begin(),若没有发现,返回-1
- // 与std::search()类似,后者返回子序列第一次出现的位置
- auto result = std::find_end(str.begin(), str.end(), pattern.begin(), pattern.end());
- if (result != str.end())
- {
- //substr()截取字符串子序列,第一个参数为开始索引,第二参数是子序列长度
- //substring(截取字符串子序列,第一个参数为开始索引,第二参数是结束索引
- //目录
- auto dirName = str.substr(0, std::distance(str.begin(), result) + 1);
- //带后缀名的文件名
- auto fileName = str.substr(std::distance(str.begin(), result) + 1);
- //不带后缀名的文件名
- fileBaseName = fileName.substr(0, fileName.size() - 4);
- }
- return fileBaseName;
- }
2、提取XML文件
首先要引入tinyxml2的头文件,tinyxml2.h和tinyxml2.cpp
xml文件内容:
<?xml version="1.0" encoding="UTF-8"?> MD5123
声明XMLDocument变量,存放xml文件
- tinyxml2::XMLDocument doc
读取xml文件
获取头节点
- XMLElement *root = doc.RootElement();
头结点的兄弟节点
- XMLElement *root1 = root->NextSiblingElement()
获取节点的id的属性
获取节点的name的属性
获取节点的文本内容
获取头结点下的head节点
- XMLElement *head = root->FirstChildElement("head")
- #include <stdio.h>
- #include <iostream>
- #include <Windows.h>
- #include <string>
- #include "tinyxml2-master/tinyxml2.h"
- using namespace std;
- using namespace tinyxml2;
- void readXML()
- {
- //声明XMLDocument变量
- tinyxml2::XMLDocument doc;
- //读取xml文件
- doc.LoadFile("demo.xml");
- //判断是否读取成功
- if (doc.Error())
- {
- printf("Load XML failed!");
- return;
- }
- //获取头节点
- XMLElement *root = doc.RootElement();
- //判断头结点有没有兄弟节点
- if (root->NextSiblingElement() != NULL)
- {
- //头结点的兄弟节点
- XMLElement *root1 = root->NextSiblingElement();
- //获取节点的id的属性
- printf("第二个一级节点%s\n", root1->Attribute("id"));
- }
- if (root->GetText() != NULL)
- {
- string rootStr = root->GetText();
- printf("第一个一级节点的内容%s\n", rootStr);
- }
- XMLElement *head = root->FirstChildElement("head");
- //获取节点的内容
- printf("head的内容%s\n", head->GetText());
- printf("head的id%s\n", head->Attribute("id"));
- printf("head的name%s\n", head->Attribute("name"));
- system("pause");
总结
今天用C++实现了提取文件名与XML文件。
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注w3xue的更多内容!