【问题标题】:no matching function for call to 'replace(std::basic_string<char>::iterator, std::basic_string<char>::iterator, char, int)'|'replace(std::basic_string<char>::iterator, std::basic_string<char>::iterator, char, int)'的调用没有匹配函数|
【发布时间】:2017-11-29 21:02:21
【问题描述】:

如何将所有\ 更改为\\

我想创建地址来处理文件:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    string str = "C:\\user\\asd";
    replace(str.begin(), str.end(), '\\', '\\\\');
    cout << str;
    return 0;
}

我收到一个错误:

F:\c++\tests\regex\main.cpp|8|error: no matching function for call to 'replace(std::basic_string::iterator, std::basic_string::iterator , 字符, int)'|

如何在 C++ 中使用 char 数组(没有函数)完成这项工作?

【问题讨论】:

  • '\\\\' 是多字节字符,不能用char 表示。 '\\\\'"\\" 不同。
  • 您的问题是关于将 / 更改为 // 但您的代码使用 \ 和 \\.
  • 谢谢,怎么办?

标签: c++ replace


【解决方案1】:

您正在使用std::replace(),它会替换一系列迭代器中的值。在这种情况下,您正在使用来自 std::string 的迭代器,因此要搜索的值和替换它的值都必须是单个 char 值。但是,'\\\\' 是一个多字节字符,因此不能用作char 值。这就是您收到编译器错误的原因。

std::string 有自己的重载replace() 方法,其中一些可以用多字符串替换部分std::string

试试这个,例如:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "C:\\user\\asd";

    string::size_type pos = 0;    
    while ((pos = str.find('\\', pos)) != string::npos)
    {
        str.replace(pos, 1, "\\\\");
        pos += 2;
    }

    cout << str;
    return 0;
}

Live demo

但是,您说您“想要创建地址来处理文件”,这对我来说意味着您想要创建一个file: URI。如果是这样,那么您需要更像这样的东西(这是一个严重的过度简化,一个 proper URI 生成器会比这个更复杂,如URIs have many rules to them,但这会让你开始) :

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

const char* safe_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:@/";

int main()
{
    string str = "C:\\user\\ali baba";

    replace(str.begin(), str.end(), '\\', '/');

    string::size_type pos = 0;
    while ((pos = str.find_first_not_of(safe_chars, pos)) != string::npos)
    {
        ostringstream oss;
        oss << '%' << hex << noshowbase << uppercase << (int) str[pos];
        string newvalue = oss.str();
        str.replace(pos, 1, newvalue);
        pos += newvalue.size();
    }

    str = "file:///" + str;

    cout << str;
    return 0;
}

Live demo

【讨论】:

  • 不要用另一个子字符串替换所有出现的子字符串,不。
猜你喜欢
  • 1970-01-01
  • 2020-07-14
  • 2018-12-05
  • 2015-06-02
  • 1970-01-01
  • 2020-07-02
  • 2015-04-28
  • 2022-01-19
  • 1970-01-01
相关资源
最近更新 更多