Delphi中關於字符串截取詳解


2020-3-30因工作需要進行字符串截取,特寫下所注意事項

delphi程序本身中的字符串截取函數:LeftStr,MidStr,RightStr ,使用時需引用單元 StrUtils;

如為不想增加程序文件的大小的話,可把這個三個函數重寫:

function RightStr(Const Str: String; Size: Word): String;
begin
  if Size > Length(Str) then Size := Length(Str) ;
    RightStr := Copy(Str, Length(Str)-Size+1, Size)
end;

function MidStr(Const Str: String; From, Size: Word): String;
begin
  MidStr := Copy(Str, From, Size)
end;

function LeftStr(Const Str: String; Size: Word): String;
begin
   LeftStr := Copy(Str, 1, Size)
end;

並結合pos,copy,length函數使用;

但問題是中用Length來取字符長度時,會將漢字當成兩個字節來計算,Copy把漢字當成兩個來處理,可能截取半個漢字,那我們如何知道是否取的是漢字呢?是否把一個漢字取完整?

在delphi中自帶ByteType函數對取出來的字符進行判斷是一個單字符還是漢字的一部分!

mbLeadByte: 漢字的第一個字節
mbTrailByte: 漢字的第二個字節
mbSingleByte: 單個的字符,不是中文字符。
如果Copy出來的是漢字的第一個字節,就再多(或少)Copy一個,湊成完整的漢字。

以下的代碼為轉自https://www.cnblogs.com/pilybird/archive/2007/12/07/986711.html

function LeftStrEx(const AText: string; ACount: Integer): string;
var
  I,ChrLen,
  BreakLen:Integer;
  IsMBCS:Boolean;
begin
   I := 1;
   BreakLen := 0;
   IsMBCS := False;
   if Length(AText)>ACount then
   begin
      while I<=ACount do
      begin
         if AText[I] in LeadBytes then
         begin
            ChrLen := CharLength(AText,I)-1;
            I:= I + ChrLen;
            //說明AText[ACount]不是一個中文字符的末尾
            if I>ACount then
            begin
               IsMBCS := True;
               BreakLen := I - ChrLen - 1;
               Break;
            end;
         end;
         //..
         Inc(I);
      end;
   end;
   //AText[ACount]不是半個中文字符
   if not IsMBCS then
      Result := LeftStr(AText,ACount)
   else
      Result := LeftStr(AText,BreakLen);
end;

  

 


免責聲明!

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



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