Search code examples
c++stringreplaceeraseerase-remove-idiom

Erase all characters in string between the first parenthesis "(" andthe last parenthesis "(" including these parentheses C++


I have a trouble to remove all the characters between the first parenthesis "(" and the last parenthesis "(" including them. Here is the test program I use to make it work, but without success...

#include <iostream>
#include <string>

using namespace std;

int main()
{

    string str = "( 1221 ( 0 0 0 ) (1224.478541112155452 (1.32544e-7 0 0 ) ) )";

    int count = 0;

    for (std::string::size_type i = 0; i < str.size(); ++i)
    {

        if (str[i] == '(')
        {
            count += 1;
        }

        cout << "str[i]: " << str[i] << endl;

        if (count <= 4)
        {

            str.erase(0, 1);
            //str.replace(0, 1, "");

        }

        cout << "String: " << str << endl;

        if (count == 4)
        {
            break;
        }

        cout << "Counter: " << count << endl;

    }


    cout << "Final string: " << str << endl;

    system("PAUSE");

    return 0;
}

In the example I have showed above, my target is (at least) to get the string:

"1.32544e-7 0 0 ) ) )"

which is extracted from original string

"( 1221 ( 0 0 0 ) (1224.478541112155452 (1.32544e-7 0 0 ) ) )"

To be more precise, I want to extract the value

"1.32544e-7"

and convert to double in order to use in calculations.

I have managed successfully to remove the

" 0 0 ) ) )"

since it is a kind of constant value.

Thank you!


Solution

  • Rephrasing the problem as "I want to extract the double immediately following the last '('", a C++ translation is pretty straightforward:

    int main()
    {
        string str = "( 1221 ( 0 0 0 ) (1224.478541112155452 (1.32544e-7 0 0 ) ) )";
    
        // Locate the last '('.
        string::size_type pos = str.find_last_of("(");
    
        // Get everything that follows the last '(' into a stream.
        istringstream stream(str.substr(pos + 1));
    
        // Extract a double from the stream.
        double d = 0;
        stream >> d;                       
    
        // Done.        
        cout << "The number is " << d << endl;
    }
    

    (Format validation and other bookkeeping left out for clarity.)