如何搜索并打印字符串中的特定部分?
我主要是从 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;
}
提前感谢您的帮助。如果您能帮助我完成代码,我将不胜感激。
I am mainly looking for a standard function from the C++ library that will help me searching inside a string for a character then print out the rest of the string starting from that found character. I have the following scenario:
#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;
}
Thanks in advance for your help. Please if you can help me completing the code, i would be grateful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以从最后一个
/
开始的字符串中提取子字符串,但为了最有效(即,避免对要打印的数据进行不必要的复制),您可以使用string::rfind
以及ostream::write
:如果您需要提取文件名并稍后使用它,而不是立即打印它,那么 bert-jan 的 或 xavier 的 答案会很好。
You could extract a substring from the string starting from the last
/
, but to be most efficient (that is, to avoid making a needless copy of the data you want to print), you can usestring::rfind
as well asostream::write
:If you needed to extract the file name and use it later instead of just print it immediately, then bert-jan's or xavier's answers would be good.
尝试
Try
您可以使用 _splitpath() 请参阅 http://msdn.microsoft.com/en- us/library/e737s6tf.aspx 来自 MSDN。
您可以使用此 STD RTL 函数将路径拆分为多个组件。
You might use _splitpath() see http://msdn.microsoft.com/en-us/library/e737s6tf.aspx form MSDN.
You can split paths into components with this STD RTL function.
基于这一行描述您的问题的目标:
您可以使用 std::filesystem 很好地做到这一点:
如果您只需要不带扩展名的文件名:
Based on this line describing the objective of your question:
You can use the std::filesystem to do it quite nicely:
If you only need the filename without the extension: