#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;
}
I am getting following error:
main.cpp: In function
'int main()': main.cpp:10:5: error: invalid conversion from 'const char*' to 'char' [-fpermissive] s[i]= "10";
Any help would be highly appreciated. Thank you.
You can find the position of A, starting from index 0 until end of the string and whenever you find, replace it with 10 using the information of both position where you found and the length of the string you would like to find in the given string.
Something like follows: 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;
}
why not use string::find() to locate the character you want to replace and then string::insert to insert a "10"? maybe not the best way, but can finish it correctly.
You code's question is that the operator[] of std::string returns a char&, and you can not assign a string literal to it.
And I think I should give you a function to implement it.
void Process(std::string& op)
{
auto pos=op.find('A');
op.erase(pos,1);
if(pos!=std::string::npos)
{
op.insert(pos,"10");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With