Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

#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.

like image 401
Animesh Bhattarai Avatar asked Dec 02 '25 00:12

Animesh Bhattarai


2 Answers

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;
}
like image 137
JeJo Avatar answered Dec 03 '25 14:12

JeJo


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");
    }
}
like image 28
con ko Avatar answered Dec 03 '25 15:12

con ko