#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 开始直到字符串结尾,每当您找到时,替换
为 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;
}
关于c++ - 如何将 'A' 之类的单个字符替换为 "10"之类的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50083706/