50字范文,内容丰富有趣,生活中的好帮手!
50字范文 > C++提取文件名与提取XML文件

C++提取文件名与提取XML文件

时间:2019-10-04 06:41:38

相关推荐

C++提取文件名与提取XML文件

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文件

doc.LoadFile("demo.xml")

获取头节点

XMLElement *root = doc.RootElement();

头结点的兄弟节点

XMLElement *root1 = root->NextSiblingElement()

获取节点的id的属性

root1->Attribute("id");

获取节点的name的属性

head->Attribute("name")

获取节点的文本内容

root1->GetText();

获取头结点下的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文件,感觉有用的同学点点关注。后续还将分享更多有用的知识。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。