c++ - 搜索 C++ 字符串并剥离文本(如果存在)

标签 c++ 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_debug".

string appl = getApplicationName();
appl.append("Info.conf");

cout << "Output of string is " << appl << endl;

在上面的代码中,applMyAppInfo.confMyAppInfo_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/

相关文章:

c++ - 我将如何清理这些If语句?

c++ - std::promise 和 std::future 的非明显生命周期问题

c++ - 创建一个模板来包装 C++ 成员函数并公开为 C 回调

c - 如何将 int 转换为十六进制,然后将其转换为字符串格式?

c++ - 错误 : CLASS_NAME has not been declared/does not name a type (c++)

c# - 平台构建器中的 DLL

java - 换行符不会在浏览器中呈现

c# - String.Intern 和 String.IsInterned 有什么区别?

java - 如何整齐地对齐字符串变量的输出?

java - 正则表达式来找到这种模式?