我必须处理两种类型的字符串:
// get application name is simple function which returns application name.
// This can be debug version or non debug version. So return value for this
// function can be for eg "MyApp" or "MyApp_debug".
string appl = getApplicationName();
appl.append("Info.conf");
cout << "Output of string is " << appl << endl;
在上面的代码中,appl
是MyAppInfo.conf
或MyAppInfo_debug.conf
。
我的要求是无论是调试版本还是非调试版本我都应该只输出一个,即 MyAppInfo.conf
。我们如何检查字符串中的 _debug
以及如果存在,我们如何去除它以便我们始终将输出字符串作为 MyAppInfo.conf
?
最佳答案
我会包装 getApplicationName()
并改为调用包装器:
std::string getCanonicalApplicationName()
{
const std::string debug_suffix = "_debug";
std::string application_name = getApplicationName();
size_t found = application_name.find(debug_suffix);
if (found != std::string::npos)
{
application_name.replace(found, found + debug_suffix.size(), "");
}
return application_name;
}
请参阅 std::string::find()
的文档和 std::string::replace()
.
关于c++ - 搜索 C++ 字符串并剥离文本(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5026735/