• 操作字符串获取文件名字


    记录一种操作字符串获取文件名字的操作方式,方便后期的使用。示例:

    输入:"D:/code/Test/Test.txt"

    输出:"Test.txt" 或者 ”Test“

     1.返回值包含类型

    设计思路:

            首先查找路径中最后一个”/“或者 ”\\“,然后再通过字符串截取的方式,获取文件名。

     代码具体实现:

    1. #include
    2. #include
    3. #define ISPATHPART(c) ((c)=='/'||(c)=='\\')
    4. std::string GetName(const std::string& strPathFile)
    5. {
    6. if (!strPathFile.empty())
    7. {
    8. int number = 0, index = 0;
    9. if (isalpha(strPathFile[0]) && strPathFile[1] == ':')
    10. {
    11. index = 1;
    12. number = index + 1;
    13. }
    14. index++;
    15. int nlen = strPathFile.length();
    16. while (index
    17. {
    18. if (ISPATHPART(strPathFile[index]))
    19. {
    20. number = index + 1;
    21. }
    22. index++;
    23. }
    24. return std::string(strPathFile.c_str()+ number, nlen-number);
    25. }
    26. return"";
    27. }
    28. int main()
    29. {
    30. std::string path = "D:/code/Test/Test.txt";
    31. path = GetName(path);
    32. return 0;
    33. }

    测试结果:

    2.返回值不包含类型

    设计思路:

            1.首先查找到最后的”/“,记录位置

            2.从字符串尾部开始遍历,查找”.“ ,并记录位置。

            3.通过对字符串的截取获取相对应的结果

    1. #include
    2. #include
    3. #define ISPATHPART(c) ((c)=='/'||(c)=='\\')
    4. std::string GetTitle(const std::string& strPathFile)
    5. {
    6. if (!strPathFile.empty())
    7. {
    8. int number = 0, index = 0;
    9. if (isalpha(strPathFile[0]) && strPathFile[1] == ':')
    10. {
    11. index = 1;
    12. number = index + 1;
    13. }
    14. index++;
    15. int nlen = strPathFile.length();
    16. while (index
    17. {
    18. if (ISPATHPART(strPathFile[index]))
    19. {
    20. number = index + 1;
    21. }
    22. index++;
    23. }
    24. if (number >= nlen)
    25. {
    26. return"";
    27. }
    28. int nt = 0;
    29. while (number
    30. {
    31. index--;
    32. if (strPathFile[index] == '.')
    33. {
    34. nt = index;
    35. break;
    36. }
    37. }
    38. return std::string(strPathFile.c_str() + number, nt - number);
    39. }
    40. return"";
    41. }

    测试结果:

  • 相关阅读:
    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