代码之家  ›  专栏  ›  技术社区  ›  Adrian

如何用CRLF替换字符串中出现的CR?

  •  1
  • Adrian  · 技术社区  · 8 年前

    我试着用 std::replace 算法:

    replace(out.begin(), out.end(), '\r', '\r\n');    // error
    replace(out.begin(), out.end(), "\r", "\r\n");    // error
    replace(out.begin(), out.end(), "\\r", "\\r\\n"); // error
    

    我总是得到参数不明确的错误。我该如何准确地说明 \r 和 \n 所以编译器不会抱怨?

    编辑:

    错误:

     could not deduce template argument for 'const _Ty &' from 'const char [5]' 
     template parameter '_Ty' is ambiguous
    'replace': no matching overloaded function found    
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Bartek Banachewicz    8 年前

    虽然原则上这可以通过一些标准/增强函数的组合来解决,但它足够具体,可以获得自己的函数,从而也可以得到自己的IMPL。可以这么简单:

    std::string cr_to_crlf(std::string const& s) {
        std::string result;
        result.reserve(s.size());
    
        for (char c : s) {
            result += c;
            if (c == '\r') {
                result += '\n';
            }
        }
        return result;
    }