如何将像'A'这样的单个字符替换为类似"10"?

How do I replace a single character like 'A' with something like "10"?

本文关键字:替换 字符 单个      更新时间:2023-10-16
#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;
}

我收到以下错误:

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

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

你可以找到A的位置,从索引 0 开始直到字符串的末尾,只要你找到,就用10replace它,使用你找到的位置和你想在给定字符串中找到的字符串长度的信息。

如下所示: 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;
}

为什么不使用string::find()找到要替换的字符,然后string::insert插入"10"? 也许不是最好的方法,但可以正确完成它。

你的代码的问题是std::stringoperator[]返回一个char&,并且你不能给它分配一个string literal

我想我应该给你一个函数来实现它。

void Process(std::string& op)
{
auto pos=op.find('A');
op.erase(pos,1);
if(pos!=std::string::npos)
{
op.insert(pos,"10");
}
}