如何将“ A”之类的单个字符替换为“ 10”之类的字符?

Ani*_*rai 3 c++ arrays replace stdstring c++11

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

int main () 
{
    string s;
    cin >> s;
    for (int i = 0; i < s.size (); i++)
    {
        if (s[i] == 'A')
        {
            s[i] = "10";
        }
        cout << s[i];
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

main.cpp: In function
'int main()': main.cpp:10:5: error: invalid conversion from 'const char*' to 'char' [-fpermissive]  s[i]= "10";
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。谢谢。

JeJ*_*eJo 5

您可以找到的位置A,从索引0开始到字符串的末尾,无论何时找到replace它,都可以10使用找到的位置以及想要在给定字符串中找到的字符串长度的信息来找到它。

如下所示:https : //www.ideone.com/dYvF8d

#include <iostream>
#include <string>

int main()
{
    std::string str;
    std::cin >> str;

    std::string findA = "A";
    std::string replaceWith = "10";

    size_t pos = 0;
    while ((pos = str.find(findA, pos)) != std::string::npos)
    {
        str.replace(pos, findA.length(), replaceWith);
        pos += replaceWith.length();
    }

    std::cout << str << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)