(引用)
{------------------------------------------------------------------------------}
{ procedure ReadStrValues }
{ }
{ 功能說明: 根據指定的分隔符將一個字符串分解為若干個子串 }
{ 如果傳遞的子串數量超過源串可以解析的字串數, 則多傳的子串將置為空串 }
{ 參 數: }
{ Str : 待分解的字符串 }
{ StrArr: 存放分解后的子串的數組, 以字符串指針數組傳遞 }
{ Ch : 分隔符定義, 缺省為 ";" }
{------------------------------------------------------------------------------}
procedure ReadStrValues(Str: string; StrArr: array of PString; Ch: Char = ';');
var
I, StrLen, StrPos, ArrLen, ArrIndex: Integer;
begin
StrLen := Length(Str); // 字符串長
ArrLen := Length(StrArr); // 待取出的字符串個數
if ArrLen = 0 then Exit; // 如果字符串指針數組中無元素,則直接退出
StrPos := 1; // 當前讀到的字符串位置
ArrIndex := 0; // 當前字符串指針數組位置
// 此處將 Str 長度加1,用于后面判斷是否已讀完整個字串
for I := 1 to StrLen + 1 do
begin
// 注意此處條件位置不可倒置(驟死式判斷)
if (I = StrLen + 1) or (Str[I] = Ch) then
begin
// 拷貝讀到的字符串
StrArr[ArrIndex]^ := Copy(Str, StrPos, I - StrPos);
StrPos := I + 1;
// 如果需要讀的字符串指針數組已完成,則退出
Inc(ArrIndex);
if ArrIndex >= ArrLen then Exit;
end;
end;
// 檢查是否所有的字符串指針都讀到了,如果沒有讀到,將被設置為空串
for I := ArrIndex to ArrLen - 1 do
StrArr[I]^ := '';
end;
{------------------------------------------------------------------------------}
{ 測試該函數 }
{------------------------------------------------------------------------------}
procedure TForm1.FormCreate(Sender: TObject);
const
SampleStr = '張三;男;41';
var
S1, S2, S3, S4: string;
begin
// 正常字串解析
S1 := 'S1'; S2 := 'S2'; S3 := 'S3'; S4 := 'S4';
ReadStrValues(SampleStr, [@S1, @S2, @S3]);
ShowMessage(Format('"%s", "%s", "%s", "%s"', [S1, S2, S3, S4]));
// 待讀字串少于源串內容測試
S1 := 'S1'; S2 := 'S2'; S3 := 'S3'; S4 := 'S4';
ReadStrValues(SampleStr, [@S1, @S2]);
ShowMessage(Format('"%s", "%s", "%s", "%s"', [S1, S2, S3, S4]));
// 待讀字串多于源串內容測試
S1 := 'S1'; S2 := 'S2'; S3 := 'S3'; S4 := 'S4';
ReadStrValues(SampleStr, [@S1, @S2, @S3, @S4]);
ShowMessage(Format('"%s", "%s", "%s", "%s"', [S1, S2, S3, S4]));
// 待讀字串為空測試
S1 := 'S1'; S2 := 'S2'; S3 := 'S3'; S4 := 'S4';
ReadStrValues(SampleStr, []);
ShowMessage(Format('"%s", "%s", "%s", "%s"', [S1, S2, S3, S4]));
// 源串為空測試
S1 := 'S1'; S2 := 'S2'; S3 := 'S3'; S4 := 'S4';
ReadStrValues('', [@S1, @S2, @S3]);
ShowMessage(Format('"%s", "%s", "%s", "%s"', [S1, S2, S3, S4]));
end;