Searching a C++ string and strip off text if present
I have to handle two types of string:
// 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_d开发者_Python百科ebug".
string appl = getApplicationName();
appl.append("Info.conf");
cout << "Output of string is " << appl << endl;
In above code appl
is MyAppInfo.conf
or MyAppInfo_debug.conf
.
My requirement is whether it is debug or non-debug version I should have output of only one i.e., MyAppInfo.conf
. How can we check for _debug
in string and if present and how do we strip of that so that we always get output string as MyAppInfo.conf
?
I would wrap getApplicationName()
and call the wrapper instead:
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;
}
See the documentation for std::string::find()
and std::string::replace()
.
string appl = getApplicationName(); //MyAppInfo.conf or MyAppInfo_debug.conf.
size_t pos = appl.find("_debug");
if ( pos != string::npos )
appl = appl.erase(pos, 6);
cout << appl;
Output is always:
MyAppInfo.conf
See sample output : http://www.ideone.com/x6ZRN
精彩评论