C++ 如何从字符串中删除特定的子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10532384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove a particular substring from a string?
提问by John
In my C++ program, I have the string
在我的 C++ 程序中,我有字符串
string s = "/usr/file.gz";
Here, how to make the script to check for .gz
extention (whatever the file name is) and split it like "/usr/file"
?
在这里,如何使脚本检查.gz
扩展名(无论文件名是什么)并将其拆分为"/usr/file"
?
采纳答案by Component 10
How about:
怎么样:
// 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());
}
回答by Aligus
回答by Dean Michael
If you're able to use C++11, you can use #include <regex>
or if you're stuck with C++03 you can use Boost.Regex (or PCRE) to form a proper regular expression to break out the parts of a filename you want. Another approach is to use Boost.Filesystem for parsing paths properly.
如果您能够使用 C++11,则可以使用,#include <regex>
或者如果您坚持使用 C++03,则可以使用 Boost.Regex(或 PCRE)来形成正确的正则表达式来分解文件名的各个部分你要。另一种方法是使用 Boost.Filesystem 正确解析路径。
回答by user8241310
void stripExtension(std::string &path)
{
int dot = path.rfind(".gz");
if (dot != std::string::npos)
{
path.resize(dot);
}
}