如何搜索和打印字符串中的特定部分
How to search and print specific parts in a String?
我主要是从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::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-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();
相关文章:
- ODBC:如何将空字符串绑定到C 中的空
- CodeBlocks字符串输出定界线
- 尝试将字符串传递到绑定的函数C
- 使用C 从定界线拆分字符串中提取整数数组
- Node-ffi 绑定到 NULL 终止的 C 字符串数组,但得到“分段错误:11”
- 字符串文字绑定到一个非常量字符指针
- 在字符串上迭代,但将定界器保持在子字符串中,包括其他规则
- 将char*绑定到字符串
- 如何函数<void(字符串消息)>绑定到成员函数?
- Sample.exe中0x7537812f处未处理的异常:0xC0020001:字符串绑定无效
- 浏览字符串并将部分行读取到类字段中
- Clang:将绑定或mem_fn与字符串::c_str和转换一起使用时出现问题
- 代码合成XSD解析/数据绑定xml字符串,而不是xml文件
- 使用带有绑定的boost字符串算法谓词
- 增强绑定和分配以将矢量转换为字符串
- 在c++中使用递归解除字符串的绑定
- C++如何创建"绑定"字符串文本替换方法?
- 从文件中读取字符串并将其不同部分保存在C++中的不同变量中
- 绑定密钥?(c)(将字符串转换为函数)
- 将C++_TCHAR绑定到SWIG接口中的C#字符串