0

I've more than 10 different strings that I want to replace. Right now, I'm using the manual method as shown in the following code.

StringReplace(StringReplace(StringReplace(StringReplace(
StringReplace(StringReplace(StringReplace(MyEditor->Text,
"one","ab",TReplaceFlags()<< rfReplaceAll << rfIgnoreCase),
"two","cd",TReplaceFlags()<< rfReplaceAll << rfIgnoreCase),
"three","ef",TReplaceFlags()<< rfReplaceAll << rfIgnoreCase),
"four","gh",TReplaceFlags()<< rfReplaceAll << rfIgnoreCase),
"five","ij",TReplaceFlags()<< rfReplaceAll << rfIgnoreCase),
"six","kl",TReplaceFlags()<< rfReplaceAll << rfIgnoreCase),
"seven","mn",TReplaceFlags()<< rfReplaceAll << rfIgnoreCase);

...so on and on.

So, I want to know how to replace many strings using more practical and flexible method. Perhaps by using a specific function ?.

Thank you very much.

1 Answer 1

1

The RTL does not have a function for that purpose. You will have to write your own, eg:

struct StringReplacePattern
{
    String OldPattern;
    String NewPattern;
};

String __fastcall MultiStringReplace(const String S, const StringReplacePattern *Patterns, int NumPatterns, TReplaceFlags Flags)
{
    String Result = S;
    for (int i = 0; i < NumPatterns; ++i)
        Result = StringReplace(Result, Patterns[i].OldPattern, Patterns[i].NewPattern, Flags);
    return Result;
}

Then you can call it like this:

StringReplacePattern patterns[] = {
    {"one", "ab"},
    {"two", "cd"},
    {"three", "ef"},
    {"four", "gh"},
    {"five", "ij"},
    {"six", "kl"},
    {"seven", "mn"},
    // and so on...
};

String S = MultiStringReplace(MyEditor->Text, patterns, ARRAYSIZE(patterns), TReplaceFlags()<< rfReplaceAll << rfIgnoreCase);
1
  • All the praises and thanks be to the God!. Like your answers beforehand, this answer is also works perfectly. You're so great, indeed. Thank you very...really much, Remy!. Oct 14, 2015 at 22:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.