如何从字符串中删除特定的子字符串?

新手上路,请多包涵

在我的 C++ 程序中,我有字符串

string s = "/usr/file.gz";

在这里,如何使脚本检查 .gz 扩展名(无论文件名是什么)并将其拆分为 "/usr/file"

原文由 John 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 549
2 个回答

怎么样:

 // Check if the last three characters match the ext.
const std::string ext(".gz");
if ( s != ext &&
     s.size() > ext.size() &&
     s.substr(s.size() - ext.size()) == ".gz" )
{
   // if so then strip them off
   s = s.substr(0, s.size() - ext.size());
}

原文由 Component 10 发布,翻译遵循 CC BY-SA 3.0 许可协议

另一个答案 的较短版本 (C++11)

 std::string stripExtension(const std::string &filePath) {
    return {filePath, 0, filePath.rfind('.')};
}

原文由 Petr Gladkikh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题