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;