记录一种操作字符串获取文件名字的操作方式,方便后期的使用。示例:
输入:"D:/code/Test/Test.txt"
输出:"Test.txt" 或者 ”Test“
设计思路:
首先查找路径中最后一个”/“或者 ”\\“,然后再通过字符串截取的方式,获取文件名。
代码具体实现:
- #include
- #include
- #define ISPATHPART(c) ((c)=='/'||(c)=='\\')
-
- std::string GetName(const std::string& strPathFile)
- {
- if (!strPathFile.empty())
- {
- int number = 0, index = 0;
- if (isalpha(strPathFile[0]) && strPathFile[1] == ':')
- {
- index = 1;
- number = index + 1;
- }
- index++;
- int nlen = strPathFile.length();
- while (index
- {
- if (ISPATHPART(strPathFile[index]))
- {
- number = index + 1;
- }
- index++;
- }
- return std::string(strPathFile.c_str()+ number, nlen-number);
- }
- return"";
- }
-
- int main()
- {
- std::string path = "D:/code/Test/Test.txt";
- path = GetName(path);
- return 0;
- }
测试结果:

2.返回值不包含类型
设计思路:
1.首先查找到最后的”/“,记录位置
2.从字符串尾部开始遍历,查找”.“ ,并记录位置。
3.通过对字符串的截取获取相对应的结果
- #include
- #include
- #define ISPATHPART(c) ((c)=='/'||(c)=='\\')
-
- std::string GetTitle(const std::string& strPathFile)
- {
- if (!strPathFile.empty())
- {
- int number = 0, index = 0;
- if (isalpha(strPathFile[0]) && strPathFile[1] == ':')
- {
- index = 1;
- number = index + 1;
- }
- index++;
- int nlen = strPathFile.length();
- while (index
- {
- if (ISPATHPART(strPathFile[index]))
- {
- number = index + 1;
- }
- index++;
- }
-
- if (number >= nlen)
- {
- return"";
- }
- int nt = 0;
- while (number
- {
- index--;
- if (strPathFile[index] == '.')
- {
- nt = index;
- break;
- }
-
- }
- return std::string(strPathFile.c_str() + number, nt - number);
- }
- return"";
- }
测试结果:

-
相关阅读:
IDEA插件开发
Docker-harbor私有仓库部署与管理
35. 搜索插入位置 --力扣 --JAVA
标准库浏览 – Part II
如何避免CMDB沦为数据孤岛?
概率图模型--贝叶斯网络与马尔可夫随机场
【CMU15-445 Part-13】Query Execution II
java实现中介者模式
数据库锁机制和我的理解
【总结】ui自动化selenium知识点总结
-
原文地址:https://blog.csdn.net/qq_39884728/article/details/139405453