Pos,PosEx学习

 

 

PosEx,Pos都是在一个字符串中搜索子串返回其索引值

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TfrmStrDemo = class(TForm)
    Edit1: TEdit;
    ListBoxMatch: TListBox;
    btnPos: TButton;
    btnPosEx: TButton;
    procedure btnPosClick(Sender: TObject);
    procedure btnPosExClick(Sender: TObject);
  private
    { Private declarations }
  public
    function CountSubStr(text,sub:string):integer;
    function CountSubStrEx(text,sub:string):integer;
  end;

var
  frmStrDemo: TfrmStrDemo;

implementation
uses
  StrUtils;

{$R *.dfm}

procedure TfrmStrDemo.btnPosClick(Sender: TObject);
begin
 ShowMessage('共有' +IntToStr(CountSubStr(ListBoxMatch.Items.Text,edit1.text))+'个');
end;

procedure TfrmStrDemo.btnPosExClick(Sender: TObject);
begin
 ShowMessage('共有' +IntToStr(CountSubStrEx(ListBoxMatch.Items.Text,edit1.text))+'个');
end;

function TfrmStrDemo.CountSubStr(text, sub: string): integer;
var
 nPos: Integer;
begin
  Result := 0;
  nPos := Pos(sub,text);
  while nPos > 0 do
  begin
     INC(Result);//加1
     text := Copy(text,nPos+Length(sub),MaxInt);
     nPos := Pos(sub,text);
  end;
end;

function TfrmStrDemo.CountSubStrEx(text, sub: string): integer;
var
 nPos: Integer;
begin
    Result := 0;
    nPos :=StrUtils.PosEx(sub,text,1);
    while nPos > 0 do
    begin
       INC(Result);
       nPos := StrUtils.PosEx(sub,text,nPos + Length (sub))
    end;

end;

end.

 

 

object frmStrDemo: TfrmStrDemo
  Left = 0
  Top = 0
  Caption = 'frmStrDemo'
  ClientHeight = 202
  ClientWidth = 447
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Edit1: TEdit
    Left = 127
    Top = 8
    Width = 121
    Height = 21
    TabOrder = 0
  end
  object ListBoxMatch: TListBox
    Left = 0
    Top = 0
    Width = 121
    Height = 202
    Align = alLeft
    ItemHeight = 13
    Items.Strings = (
      'one'
      'two'
      'three'
      'four'
      'five'
      'six'
      'seven'
      'eight')
    TabOrder = 1
    ExplicitLeft = 16
    ExplicitTop = 32
    ExplicitHeight = 113
  end
  object btnPos: TButton
    Left = 254
    Top = 8
    Width = 83
    Height = 25
    Caption = 'Count with pos'
    TabOrder = 2
    OnClick = btnPosClick
  end
  object btnPosEx: TButton
    Left = 341
    Top = 8
    Width = 98
    Height = 25
    Caption = 'Count with PosEx'
    TabOrder = 3
    OnClick = btnPosExClick
  end
end

 

 

posted @ 2012-02-06 22:49  TryHard  阅读(1591)  评论(0编辑  收藏  举报