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.

4

1 回答 1

1

RTL 没有用于此目的的功能。您必须自己编写,例如:

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;
}

然后你可以这样称呼它:

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);
于 2015-10-14T21:13:25.487 回答