利用替换字符串的函数StringReplace删除字符串中指定的字符或字符串

标题有点长,呵呵~

利用StringReplace函数可以删除字符串中指定的字符(字符串),下面是一个小例子:

删除字符串中的'bad'字符串:

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses
 6   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 7   Dialogs, StdCtrls, Buttons;
 8 
 9 type
10   TForm1 = class(TForm)
11     btn1: TBitBtn;
12     edt1: TEdit;
13     procedure btn1Click(Sender: TObject);
14   private
15     { Private declarations }
16   public
17     { Public declarations }
18   end;
19 
20 var
21   Form1: TForm1;
22 
23 implementation
24 
25 {$R *.dfm}
26 
27 procedure TForm1.btn1Click(Sender: TObject);
28 var
29   original      :string;
30   AfterDelete   :string;
31 begin
32   original := edt1.Text;
33   AfterDelete :=  StringReplace(original,'bad','',[rfReplaceAll]);
34   ShowMessage(AfterDelete);
35 end;
36 
37 end.
38 

函数的描述:

From SysUtils.pas

	function StringReplace(const S: string;
		const OldPattern: string;
		const NewPattern: string;
		Flags: TReplaceFlags): string; overload;

Unit: SysUtils

Type: function

Visibility: public

 

 Description

Replaces occurrences of a substring within a string.


StringReplace replaces occurrences of the substring specified by OldPattern with the substring specified by NewPattern in the string S.

Flags is a SysUtils.TReplaceFlags type parameter. If rfIgnoreCase is set, the replacement is case-sensitive; otherwise case is ignored. If rfReplaceAll is on, all occurrences of OldPattern are replaced; if not, only the first occurrence is replaced.

Note:  The parameters S, OldPattern, NewPattern, and the return value are of type UnicodeString. To do the replacement in an AnsiString context, use the StringReplace function. Also, to do the replacement in a WideString context, use the WideStringReplace function.
Note:  Recursive replacement of substrings is not supported. This means that if the substitution of OldPattern results in a new match for NewPattern, that match is not replaced.

To replace all occurrences of the substring within the string, you may also use the ReplaceStr function to do a case-sensitive search, or ReplaceText to do a case-insensitive search.

{☆推荐☆:返利网,网上购物拿返利,省钱新门道}

原文地址:https://www.cnblogs.com/dabiao/p/1665541.html