1

我主要是从 C++ 库中寻找一个标准函数,它可以帮助我在字符串中搜索一个字符,然后从找到的字符开始打印出字符串的其余部分。我有以下情况:

#include <string>

using std::string;

int main()
{
     string myFilePath = "SampleFolder/SampleFile";

     // 1. Search inside the string for the '/' character.
     // 2. Then print everything after that character till the end of the string.
     // The Objective is: Print the file name. (i.e. SampleFile).

     return 0;
}

在此先感谢您的帮助。如果您能帮我完成代码,我将不胜感激。

4

5 回答 5

4

您可以从从 last 开始的字符串中提取子字符串/,但为了最有效(即,避免对要打印的数据进行不必要的副本),您可以使用string::rfind以及ostream::write

string myFilePath = "SampleFolder/SampleFile";

size_t slashpos = myFilePath.rfind('/');

if (slashpos != string::npos) // make sure we found a '/'
    cout.write(myFilePath.data() + slashpos + 1, myFilePath.length() - slashpos);
else
    cout << myFilePath;

如果您需要提取文件名并稍后使用它而不是立即打印它,那么bert-janxavier 的答案会很好。

于 2011-11-26T09:51:11.727 回答
3

尝试

size_t pos = myFilePath.rfind('/');
string fileName = myFilePath.substr(pos);
cout << fileName;
于 2011-11-26T09:52:58.260 回答
0

您可以使用 _splitpath() 请参阅MSDN 中的http://msdn.microsoft.com/en-us/library/e737s6tf.aspx 。

您可以使用此 STD RTL 功能将路径拆分为组件。

于 2011-11-26T10:16:01.730 回答
0
 std::cout << std::string(myFilePath, myFilePath.rfind("/") + 1);
于 2011-11-26T09:52:29.087 回答
0

根据描述您问题目标的这一行:

// The Objective is: Print the file name. (i.e. SampleFile).

您可以使用 std::filesystem 做得很好:

#include <filesystem>
namespace fs = std::experimental::filesystem;

fs::path myFilePath("SampleFolder/SampleFile");
fs::path filename = myFilePath.filename();

如果您只需要没有扩展名的文件名:

#include <filesystem>
namespace fs = std::experimental::filesystem;

myFilePath("SampleFolder/SampleFile");
fs::path filename = myFilePath.stem();
于 2019-08-22T23:26:02.063 回答