I have command string and want to find a pattern in it.If present i have to remove certain characters and retain the other characters as it is in the command string.

string aDir("bin/kwp-init start -t1 -uwelcome@mails.com -ppasstoks@123 -v");
string search_char ("@");
size_t found=0;
found = aDir.find_first_of(search_char);
cout <<"@ is found at:"<<found<<endl;
if (found!=string::npos){
    cout<<"now :"<<aDir <<endl;
    aDir.erase(found);
}
else {
    aDir.clear();         /* str is all whitespace*/
}
cout<<"then:"<<aDir<<endl;

Actual output from code is : bin/kwp-init restart -t1 -uwelcome

Expected output is : bin/kwp-init restart -t1 -uwelcome -ppasstoks@123 -v

Suggest me a solution!!

Recommended Answers

All 4 Replies

One way to do it is to do two finds

size_t found1=0;
size_t found2=0;
found1 = aDir.find_first_of(search_char);
cout <<"@ is found at:"<<found1<<endl;
if (found1!=string::npos)
{
    cout<<"now :"<<aDir <<endl;
    found2 = aDir.find('-', found1+1);
    aDir = aDir.substr(0,found1) + aDir.substr(found2-1);
}

Of course you may need to do it a little differently if the second find fails, such as use temp strings to old the sub strings.

>>aDir.erase(found);

Look at string.erase function prototype. By that command, you are erasing all elements starting at the position found. What you need is this aDir.erase(found,1);

You can try this also:-

std::string performanceDataMap::replaceSubString (std::string stringToModify, 
                                                   std::string oldSubString, 
                                                   std::string newSubString)
{
    size_t foundAt= 0;
    while((foundAt = stringToModify.find(oldSubString)) != std::string::npos)
    {
        stringToModify.replace(foundAt, oldSubString.length(), newSubString);
    }
    return stringToModify;
}

and call

newSubString = "";
std::string performanceDataMap::replaceSubString (std::string stringToModify, 
                                                   std::string oldSubString, 
                                                   std::string newSubString)
{
    size_t foundAt= 0;
    while((foundAt = stringToModify.find(oldSubString)) != std::string::npos)
    {
        stringToModify.replace(foundAt, oldSubString.length(), newSubString);
    }
    return stringToModify;
}
and call 
C++ Syntax (Toggle Plain Text)
newSubString = "";
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.