【问题标题】:How to return position of last char occurance?如何返回最后一个字符出现的位置?
【发布时间】:2016-06-10 08:44:04
【问题描述】:

我正在使用WDL_String 容器来管理 C++ 框架中的字符串。我需要拆分一个字符串(分隔符\)并获取最后一次出现。

我可以使用原生方法:

mFilePath.DeleteSub(mLastOccPosition, mFilePath.GetLength());

替换字符串,但我不知道如何捕捉mLastOccPosition

所以如果我有这个字符串:

D:\\Google Drive\\My Files\\Test.zip

我需要返回Test.zip。在 C++ 中执行此操作的最佳方法是什么?

【问题讨论】:

  • @F.bernal:我没有使用string
  • 使用 const char *Get() const 然后创建你的标准字符串
  • 如果我没记错的话,根据你链接的代码,mFilePath.get_filepart()不是给你你想要的吗?

标签: c++ string split


【解决方案1】:

如果sstd::string 的一个实例,那么s.find_last_of('\\') 会这样做。

如果找不到则返回std::string::npos

然后您可以使用std::string::substr 来提取您需要的位。

【讨论】:

  • 正如我所说,我不使用字符串。但是 WDL_String。我可以从 WDL_String 获得char*
  • 嗯,你确实要求最好的方法,那可能是写std::string s(/*the function that gets the char* */),然后从那里开始。从头开始构建提取代码是没有意义的。
  • 这样的东西好看吗? (我不需要任何对字符串的引用):(string(mFilePath.Get())).find_last_of('\\')
  • 就可以了。 (尽管如果您想使用它来提取文件名,您可能希望保留该字符串)。请注意,std::string::npos 是一个常量,不需要字符串实例。
猜你喜欢
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 2021-11-22
  • 2014-03-07
  • 2021-02-07
相关资源
最近更新 更多