C++功能模块1:find_last_of()解析文件名

想要从一个路径加文件名的字符串里解析出文件名,可以利用c++标准库的string::find_last_of()函数:

//因为find_last_of返回的分隔符“/”的位置,+1是为了丢掉“/”
string fileName = pathAndFileName.substr(pathAndFileName.find_last_of("/")+1);

注意:
1).find_last_of()
输入参数可以为字符串、也可以为单独一个字符;
但是要注意的是,当输入参数为字符串时,该函数从后往前匹配,只要匹配上字符串中的任意一个字符,就会返回该字符的位置。
2).substr()
字符串截取函数。当输入仅1个位置参数时,截取的是从该位置到最后的部分
当输入为2个位置参数时,截取的是2个位置中间的部分。

同理,如果只想要截取路径部分:

//因为find_last_of返回的分隔符“/”的位置,+1是为了丢掉“/”
string fileName = pathAndFileName.substr(0,pathAndFileName.find_last_of("/"));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 `std::string` 的 `substr` 函数来删除最后一行。这个函数接受两个参数,第一个参数是起始位置,第二个参数是要删除的字符数。 以下是使用 `std::istreambuf_iterator` 和 `std::string` 的 `substr` 函数来获取文件内容并删除最后一行的示例代码: ```c++ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string filename = "example.txt"; string content = ""; ifstream input(filename); if (input) { content.assign((istreambuf_iterator<char>(input)), (istreambuf_iterator<char>())); } input.close(); // Find the last newline character size_t last_newline_index = content.find_last_of("\n"); // Remove the last line from the content string if (last_newline_index != string::npos) { content = content.substr(0, last_newline_index); } cout << "Content without the last line:\n" << content << endl; return 0; } ``` 在这个示例中,我们首先定义了文件名和一个字符串来存储文件内容。我们打开文件并检查文件是否成功打开。如果文件已成功打开,则使用 `std::istreambuf_iterator` 一次性获取整个文件的内容,并将其存储在内容字符串中。 接下来,我们使用 `find_last_of` 函数找到最后一个换行符的位置。如果找到了该字符,则使用 `substr` 函数删除最后一行。最后,我们关闭文件并输出不包括最后一行的内容字符串。 请注意,在使用 `substr` 函数时,我们将位置 0 作为第一个参数,以确保字符串中的所有内容都被包含在内。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值