如何搜索和打印字符串中的特定部分

How to search and print specific parts in a String?

本文关键字:字符串 定部 打印 何搜索 搜索      更新时间:2023-10-16

我主要是从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;
}

提前感谢你的帮助。请如果你能帮助我完成代码,我将不胜感激。

您可以从从最后一个/开始的字符串中提取子字符串,但为了最有效(即避免对您想要打印的数据进行不必要的复制),您可以使用string::rfindostream::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-jan或xavier的答案将是很好的。

Try

size_t pos = myFilePath.rfind('/');
string fileName = myFilePath.substr(pos);
cout << fileName;
 std::cout << std::string(myFilePath, myFilePath.rfind("/") + 1);

您可以使用_splitpath(),参见http://msdn.microsoft.com/en-us/library/e737s6tf.aspx form MSDN。

您可以使用这个STD RTL函数将路径拆分为组件。

基于这一行描述你问题的目的:

// 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();