I want to know how I can do this:

  1. Find "sqrt" in a string
  2. Replace "sqrt" with only "#"

I have the following code but its not working. Why?

size_t found = 0;
found = modifiedExpr.find("sqrt");
if(found!=std::string::npos)
{
    modifiedExpr.replace(modifiedExpr.find(sqrt),sqrt.length(),"#");
}

Recommended Answers

All 5 Replies

Whats is sqrt in modifiedExpr.replace(modifiedExpr.find(sqrt),sqrt.length(),"#");? Is it a string? You should be able to do:

string sqrt = "sqrt";
size_t pos = 0;
while((pos = modifiedExpr.find(sqrt, pos)) != std::string::npos)
{
    modifiedExpr.replace(pos, sqrt.size(), "#")
}

Hi joemeister.so, you know the string to be replaced no problem just follow this code you will get the output.

found = modifiedExpr.find("sqrt");
if (found != std::string::npos)
{
    modifiedExpr.replace(found, 4, "#");
}

it will work

Hi joemeister.so, you know the string to be replaced.

found = modifiedExpr.find("sqrt");
if (found != std::string::npos)
{
    modifiedExpr.replace(found, 4, "#");
}

no problem just follow this code you will get the output.

You never update the found variable so multiple instances will not be modified. Here is an example that does what I expect you want:

#include <iostream>
#include <string>

int main () {
    const std::string fname = "sqrt";
    const size_t len = fname.size ();

    std::string expr = "sqrt(81) + 14 * sqrt(4)";
    size_t idx = expr.find (fname);

    std::cout << "Original : " << expr << std::endl;

    while (idx != std::string::npos) {
        expr.replace (idx, len, "#");
        std::cout << "Updated  : " << expr << std::endl;
        idx = expr.find (fname);
    }

    std::cout << "Final    : " << expr << std::endl;

    return 0;
}

The output is:

Original : sqrt(81) + 14 * sqrt(4)
Updated  : #(81) + 14 * sqrt(4)
Updated  : #(81) + 14 * #(4)
Final    : #(81) + 14 * #(4)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.