Link to home
Start Free TrialLog in
Avatar of xxg4813
xxg4813

asked on

Extract specfic tokens from a CString

Hi,

I have a CString which likes "{Projectname field} is <Projectname value> ... {[[Editor]]} ..."

There are 3 cases for a token:
1. inside "{}";
2. inside "<>";
3. inside "{[[]]}".

I want to extract them all and replace them with the actual value.

Sample codes will be greatly appreciated.

Thanks!
Avatar of jkr
jkr
Flag of Germany image

You could use
void ReplaceInBetween ( CString& rstrLine, CString& rstrSubst, LPCTSTR pszStart, LPCTSTR pszEnd) {

    int nStart = rstrLine.Find(pszStart);

    if ( -1 == nStart) return;

    int nEnd = rstrLine.Find(pszStart);

    if ( -1 == nStart) return;

    CString strFront = rstrLine.Left(nStart - 1);
    CString strBack = rstrLine.Left(nEnd + lstrlen(pszEnd) + 1);

    rstrLine = strFront + rstrSubst + strBack;
}

and call it like

CString str = "{Projectname field} is <Projectname value> ... {[[Editor]]} ...";
CString strSubst = "Some real Value";

ReplaceInBetween(str,strSubst,"{[[","]]}");
if string really contains literally  "{Projectname field} is <Projectname value> ... {[[Editor]]} ..."
then you can use CString::Replace() function, something like

CString str = "{Projectname field} is <Projectname value> ... {[[Editor]]} ...";

str.Replace("{Projectname field}", theRealProjName);

....etcetera...
Avatar of xxg4813
xxg4813

ASKER

Jkr,
I see your point but my problem is that I need to replace 3 caess in a same traveral of the string, i.e., need to extrace content between "{}", "<>", and "{[[]]}" at the same time. Could you revise your code a little bit to handle the 3 cases at the same time?

Jaime,
The content between can be changed with a lot of choices. It's not fixed.



>>I need to replace 3 caess in a same traveral of the string

That can't be done at once - what about

ReplaceInBetween(str,strSubst,"{[[","]]}");
ReplaceInBetween(str,strSubst,"{","}");
ReplaceInBetween(str,strSubst,"[","]");

?

BTW, a lil' correction:

void ReplaceInBetween ( CString& rstrLine, CString& rstrSubst, LPCTSTR pszStart, LPCTSTR pszEnd) {

   int nStart = rstrLine.Find(pszStart);

   if ( -1 == nStart) return;

   int nEnd = rstrLine.Find(pszEnd);

   if ( -1 == nStart) return;

   CString strFront = rstrLine.Left(nStart - 1);
   CString strBack = rstrLine.Left(nEnd + lstrlen(pszEnd) + 1);

   rstrLine = strFront + rstrSubst + strBack;
}
Avatar of xxg4813

ASKER

JKR,

To traverse 3 times the whole CString is unacceptable. And your code can only replace one instance for each case.

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you xxg4813 - lloking foward to hekp you again in the future - I think you get the idea...