0

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(),"#");
}
4
Contributors
5
Replies
27
Views
2 Years
Discussion Span
Last Post by L7Sqr
0

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(), "#")
}
0

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, "#");
}

Edited by Naveen508: a mistake

0

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.

0

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)

Edited by L7Sqr

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.