形如“c://User//1.tar.gz” 截取出1.tar 用c++写出代码示例
时间: 2023-07-31 12:07:37 浏览: 39
可以使用C++标准库中的字符串处理函数和算法来实现,具体示例代码如下:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string path = "c://User//1.tar.gz";
size_t pos = path.find_last_of("/\\"); // 找到最后一个'/'或'\\'的位置
if (pos != string::npos) {
string filename = path.substr(pos + 1); // 截取文件名和扩展名
pos = filename.find_last_of("."); // 找到最后一个'.'的位置
if (pos != string::npos) {
string name = filename.substr(0, pos); // 截取文件名
cout << name << endl; // 输出结果:1.tar
}
}
return 0;
}
```
这段代码首先使用`string::find_last_of`函数找到最后一个'/'或'\\'的位置,然后使用`string::substr`函数截取文件名和扩展名。接着再次使用`string::find_last_of`函数找到最后一个'.'的位置,最后使用`string::substr`函数截取文件名。最终输出结果为1.tar。