整理一組常用字串處理函數,涵蓋左右擷取、替換、去除空白/指定字元、自動補零編碼,可直接複製至專案通用單元。
// 擷取左側 N 字元
function LeftStr(S: string; Count: Integer): string;
begin Result := Copy(S, 1, Count); end;
// 擷取右側 N 字元
function RightStr(S: string; Count: Integer): string;
begin Result := Copy(S, Length(S) - Count + 1, Count); end;
// 字串替換 (不區分大小寫)
function ReplaceStr(S, OldStr, NewStr: string): string;
var i, j: Integer; ss: string;
begin
i := 1; ss := ''; j := Length(OldStr);
while i <= Length(S) do
if LowerCase(Copy(S, i, j)) = LowerCase(OldStr) then
begin ss := ss + NewStr; Inc(i, j); end
else begin ss := ss + S[i]; Inc(i); end;
Result := ss;
end;
// 去除左側空白
function LTrim(S: string): string;
begin S := S + '*'; S := Trim(S); Delete(S, Length(S), 1); Result := S; end;
// 去除右側空白
function RTrim(S: string): string;
begin S := '*' + S; S := Trim(S); Delete(S, 1, 1); Result := S; end;
// 刪除左側所有指定字元
function LDelete(S, Sub: string): string;
begin while LeftStr(S, 1) = Sub do Delete(S, 1, 1); Result := S; end;
// 刪除右側所有指定字元
function RDelete(S, Sub: string): string;
begin Sub := Copy(Sub, 1, 1); while RightStr(S, 1) = Sub do Delete(S, Length(S), 1); Result := S; end;
// 刪除所有指定字元
function MDelete(S, Sub: string): string;
begin Sub := Copy(Sub, 1, 1); while Pos(Sub, S) > 0 do Delete(S, Pos(Sub, S), 1); Result := S; end;
// 自動補零編碼 (如 000123)
function GetCodeNo(NoStr: string; NoLen: Integer): string;
begin
NoStr := Trim(NoStr);
Result := Copy('00000000000000000000', 1, NoLen - Length(NoStr)) + NoStr;
end;
SysUtils.Trim、StrUtils.LeftStr/RightStr、SysUtils.StringReplace (支援 rfReplaceAll, rfIgnoreCase) 已涵蓋大部分需求,優先使用標準庫。GetCodeNo 適用於單號、編號固定長度格式化。