For the string: "Number(1234)". I am looking for to extract "1234" and "Number"
I have understand that I need to know where the positions is for ex "(" and ")".
The code I have done so far look like this:

std::string Value10 = "Number(1234)";

size_t found1;
size_t found2;

found1 = Value10.find("(");
found2 = Value10.find(")");

So "(" has position 6 and ")" has postion 11. When knowing these positions. What will be the next step to do to extract "1234" ?

Re: find() 80 80

Use substr(), to extract '1234', you could do:

const std::string Value10 = "Number(1234)";

const size_t start = Value10.find("(");
const size_t end = Value10.find(")");

const std::string extracted = Value10.substr(start + 1, end - start - 1);

cout << "extracted: " << extracted.c_str() << endl;

In same, fashion you can extract 'Number' once you have a valid value for 'start' .
Note that, in case string::find() does not find any match, it returns the value std::string::npos, i.e. prepare to handle that case also, when you are looking up matches to extract sub-strings.

Re: find() 80 80
Use str.substr 

using namespace std;
int main()
        string str;
        string str1 = "This is the solution (143878932)";
        size_t  p1;
        size_t  p2;

        p1 = str1.find('(');
        str = str1.substr(0,p1-1);
        p2 = str1.find(')');
        str = str1.substr(p1,p2);
        return 0;
Re: find() 80 80

This is an example for extract the "23" from the string "OBJECT_NUMCON(23);"

Instruction[3] is "OBJECT_NUMCON" so Instruction[3].length() is equal to 10

Reader:: SetObjNumConn(string line)
    char *str = NULL; // Set a container pointer
    int length;

    size_t found;

    found = line.find(")"); // the first ocurrence of  ")"

    str = new char[int(found)-(this->Instruction[3].length()+1)]; // Set enough memory 
// 13 (")") -11 (length = 2

/**** THIS IS WHAT YOU NEED *****/
    length = line.copy(str, int(found)-(this->Instruction[3].length()+1),this->Instruction[3].length()+1);

// length = line.copy("container","number of character", "start from")
// this will copy the number of characters you desire from the point of the string you want in the container.



    delete [] str;
Re: find() 80 80

The substring that took 2 arguments did work well. So knowing start and end value can be a good way to extract strings.


Re: find() 80 80

In addition to find(), there are also other std::string functions you may find useful, i.e.
find_first_not_of(), find_first_of(), find_last_not_of(), find_last_of(), rfind()

Be a part of the DaniWeb community

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