在 Delphi 開發中,經常需要從字串中提取特定字符,例如單詞或漢字。本文介紹兩個實用的函數:StrToWordList 用於提取英文單詞與數字,StrToHanZiList 專門提取漢字。兩者都自動去重,適合文本分析、關鍵字提取等場景。
此函數將輸入字串轉為小寫,保留字母、數字、撇號與連字符,其餘字符替換為空格,最後以空格分隔並存入 TStringList,且自動過濾以數字或符號開頭的項目。
procedure StrToWordList(str: string; var List: TStringList);
var
p: PChar;
i: Integer;
begin
if List = nil then List := TStringList.Create;
List.Clear;
List.Sorted := True;
List.Duplicates := dupIgnore;
p := PChar(str);
while p^ <> #0 do
begin
case p^ of
'A'..'Z': p^ := Chr(Ord(p^) + 32); // 大寫轉小寫
'a'..'z', '0'..'9', '''', '-': ; // 保留字母、數字、撇號、連字符
else p^ := #32; // 其他替換為空格
end;
Inc(p);
end;
List.Delimiter := #32;
List.DelimitedText := str;
// 移除以數字、撇號、連字符開頭的項目
for i := List.Count - 1 downto 0 do
if CharInSet(List[i][1], ['0'..'9', '-', '''']) then
List.Delete(i);
end;
利用 Unicode 範圍 #$4E00..#$9FA5 判斷漢字,逐字符掃描並加入列表,同樣啟用排序與去重。
procedure StrToHanZiList(str: string; var List: TStringList);
var
p: PWideChar;
begin
if List = nil then List := TStringList.Create;
List.Clear;
List.Sorted := True;
List.Duplicates := dupIgnore;
p := PWideChar(str);
while p^ <> #0 do
begin
case p^ of
#$4E00..#$9FA5: List.Add(p^); // 基本漢字區
end;
Inc(p);
end;
end;
var
WordList, HanziList: TStringList;
begin
WordList := TStringList.Create;
HanziList := TStringList.Create;
try
StrToWordList('Hello World! 你好 123-test', WordList);
StrToHanZiList('Hello World! 你好 123-test', HanziList);
// WordList: hello, test, world
// HanziList: 你, 好
finally
WordList.Free;
HanziList.Free;
end;
end;
TStringList 若為 nil 會自動建立,調用者需負責釋放。