Pages

Sunday, December 11, 2011

How to replace string in delphi


To replace string in delphi, we can use 'StringReplace' function. The pattern is
function StringReplace ( const SourceString, 
OldPattern, NewPattern : string; 
Flags : TReplaceFlags ) : string;

It replaces the first or all occurences of a substring 'OldPattern' in 'SourceString' with 'NewPattern' according to 'Flags' settings.
There are two Flags can be applied. It may be none, one, or both of these values:
rfReplaceAll  : Change all occurrences
rfIgnoreCase  : Ignore case when searching
 
Below is the example code:
var
  before, after : string;
begin
  // Try to replace all occurrences of a or A to THE
  before := 'It is a kind of fruit';
  after  := StringReplace(before, ' a ', ' THE ',
                          [rfReplaceAll, rfIgnoreCase]);
  ShowMessage('Before = '+before);
  ShowMessage('After  = '+after);
end;
It will output this alert
Before = It is a kind of fruit
After  = It is THE kind of fruit

No comments:

Post a Comment

Don't Forget To Join Our Community
×
Widget