使用 CString 库函数的主字符串中的子字符串



使用 CString 库函数从主字符串复制子字符串。

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

现在,我想将Instance='SMS/MMS' AND Folder='inbox'FilterCriteria复制到o_filteredFilterCriteria

预期成果:

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

程序:

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. 

我也搜索了一个等价物。

像这样使用std::string

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

等效于如下所示CStringMFC :

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

我想FindMid一起切割就可以了。请参阅以下示例以更好地理解。

我有一个CString作为路径= _T("StackOverflow是程序员的最佳平台。 我只希望字符串为"StackOverflow 是最好的"。所以首先我找到"平台" 然后切掉那部分。

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."

最新更新