首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

Delphi 通用字串處理函數庫:LeftStr、RightStr、ReplaceStr、Trim 系列

     編輯:關於SqlServer

整理一組常用字串處理函數,涵蓋左右擷取、替換、去除空白/指定字元、自動補零編碼,可直接複製至專案通用單元。

函數清單

// 擷取左側 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;

使用提示

  • Delphi 內建 SysUtils.Trim、StrUtils.LeftStr/RightStr、SysUtils.StringReplace (支援 rfReplaceAll, rfIgnoreCase) 已涵蓋大部分需求,優先使用標準庫。
  • 上述函數為教學/舊版本相容性保留,新專案建議直接呼叫 RTL 函數。
  • GetCodeNo 適用於單號、編號固定長度格式化。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved