substring from main string using CString library functions

Viewed 10640

Copy a substring from main string using CString library functions.

CString  FilterCriteria ="MESSAGE=2 AND READ = 2 AND Instance=\'SMS/MMS\' 
AND Folder=\'inbox\'";
CString  o_filter;

Now, i want to copy Instance=\'SMS/MMS\' AND Folder=\'inbox\' from FilterCriteria to o_filteredFilterCriteria.

Expected result:

o_filter = Instance=\'SMS/MMS\' AND Folder=\'inbox\'.

Program:

int Pos = FilterCriteria.find(instance); 
int First_Pos = FilterCriteria.find("'");
string temp_str = FilterCriteria.substr(First_Pos+1);
string temp_str =FilterCriteria.
int Second_Pos = temp_str.find("'");  

string tempInstance = FilterCriteria.substr(Pos, First_Pos+Second_Pos-
Pos+2);

temp_str = "";

Pos = FilterCriteria.find(folder);// folder position
string Fold_Str = FilterCriteria.substr(Pos);//string after the folder 
First_Pos = Fold_Str.find("'");// first occurence of string
temp_str = Fold_Str.substr(First_Pos+1);// string after '
Second_Pos = temp_str.find("'");// first occurence of ' in string after '
string tempFolder=originalFilterCriteria.substr(Pos, First_Pos+Second_Pos-
Pos+2);

if ( !tempInstance.isEmpty())
{
    o_filter = " AND ";
    o_filter += tempInstance;
}

if (!tempFolder.isEmpty())
{
    o_filter = " AND ";
    o_filter += tempFolder;
}

This code works for string.h library. The same code doesn't work for CString 
functions as CString library doesn't have substr() function. 
2 Answers

I have also searched for an equivalence.

A std::string used like this:

stdString.substr(begin, end - begin + 1);

is equivalent to a MFC CString used like this:

mfcString.Mid(begin, end - begin + 1);

//or
mfcString.Right(mfcString.GetLength() - begin).Left(end - begin + 1);

I guess Find and cut with Mid will do the trick. See the below example for a better understanding.

I have a CString as path = _T("StackOverflow is the best platform for the programmer.") I want the string as "StackOverflow is the best " only. So first I find "platform" then cut the portion.

CString path = _T("StackOverFlow is the best platform for the programmer.");
int pos = path.Find(_T("platform"));
path = path.Mid(0, pos);

// Output:
// path = "StackOverflow is the best "

// or

int length = path.GetLength();
pos = path.Find(_T("platform"));
path = path.Mid(pos, length);

// Output:
// path = "platform for the programmer."
Related