根據條件把一個字符串拆分成幾個字符串


用到的函數:

function pos(Substr:string; S: string):string;  //函數返回子字符串第一次出現在制定字符串中的索引值。

copy()   // 復制字符串

delete() //刪除字符串中的一部分

 

思路:利用Pos函數定一個范圍,然后再COPY,最后刪了這個已經復制的部分,再進行下一個索引,如此循環。

 

例:

分下列字符串,DELPHI的:

ABCD           VAR           1234

這是要拆分的一行字符串, 字符串之間有N個空格這樣子.

 

const

S = 'ABCD VAR 1234';
var
p: integer;
str,rs: string;
begin
rs = S;
p := Pos(' ', rs);
while(p <> 0)
begin
str := Copy(S,p,Length(rs));
Delete(S,1,p);
ListBox1.Items.Add(str);
p := Pos(' ', rs);
end;
end;

例2

在要求用戶輸入GUID后,{E22ACEBC-DBFB-4F8C-BA76-D24151ECFD52},
我想將它存入TGUID中,但StringToGUID卻不能用,那我就想將它轉換成幾個字符串,“E22ACEBC","DBFB","BA76",

uses StrUtils;

procedure StrToStrings(S: AnsiString; Sep: AnsiString; const List: TStrings);
var
  I, L: Integer;
  Left: AnsiString;
begin
  Assert(List <> nil);
  List.Clear;
  L := Length(Sep);
  I := Pos(Sep, S);
  while (I > 0) do
  begin
    Left := LeftStr(S, I - 1);
    List.Add(Left);
    Delete(S, 1, I + L - 1);
    I := Pos(Sep, S);
  end;
  if S <> '' then
    List.Add(S);
end;

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM