C++ string template library

后端 未结 10 1116
清酒与你
清酒与你 2020-12-16 01:23

I want simple C++ string based template library to replace strings at runtime.

For example, I will use

string template = \"My name is {{name}}\";
         


        
10条回答
  •  别那么骄傲
    2020-12-16 02:12

    If you have a function that replaces all occurrences of a string with another string:

    std::string replace_all(std::string str, const std::string &remove, const std::string &insert) 
    {
        std::string::size_type pos = 0;
        while ((pos = str.find(remove, pos)) != std::string::npos)
        {
            str.replace(pos, remove.size(), insert);
            pos++;
        }
    
        return str;
    }
    

    Then you can do this:

    std::string pattern = "My name is {{first_name}} {{last_name}} and I live in {{location}}";
    
    std::string str = replace_all(replace_all(replace_all(pattern, 
                           "{{first_name}}", "Homer"), 
                           "{{last_name}}", "Simpson"), 
                           "{{location}}", "Springfield");
    

提交回复
热议问题