strrchr的C ++字符串等效 [英] C++ string equivalent for strrchr

查看:135
本文介绍了strrchr的C ++字符串等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C字符串我将编写以下代码以从文件路径获取文件名:

Using C strings I would write the following code to get the file name from a file path:

#include <string.h>

const char* filePath = "dir1\\dir2\\filename"; // example
// extract file name (including extension)
const char* fileName = strrchr(progPath, '\\');
if (fileName)
  ++fileName;
else
  fileName = filePath;

如何对C ++字符串做同样的事情? (即使用 std :: string from #include< string>

How to do the same with C++ strings? (i.e. using std::string from #include <string>)

推荐答案

最接近的等价物是 rfind

The closest equivalent is rfind:

#include <string>

std::string filePath = "dir1\\dir2\\filename"; // example
// extract file name (including extension)
std::string::size_type filePos = filePath.rfind('\\');
if (filePos != std::string::npos)
  ++filePos;
else
  filePos = 0;
std::string fileName = filePath.substr(filePos);

请注意, rfind 字符串(或 npos ),而不是指针。

Note that rfind returns an index into the string (or npos), not a pointer.

这篇关于strrchr的C ++字符串等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆