Delphi中关于字符串截取详解
<p>2020-3-30因工作需要进行字符串截取,特写下所注意事项</p><p>delphi程序本身中的字符串截取函数:LeftStr,MidStr,RightStr ,使用时需引用单元 StrUtils;</p>
<p>如为不想增加程序文件的大小的话,可把这个三个函数重写:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:delphi;gutter:true;"><span style="color: rgba(51, 102, 255, 1)">function RightStr(Const Str: String; Size: Word): String;</span>
begin
if Size > Length(Str) then Size := Length(Str) ;
RightStr := Copy(Str, Length(Str)-Size+1, Size)
end;
<span style="color: rgba(51, 102, 255, 1)">function MidStr(Const Str: String; From, Size: Word): String;</span>
begin
MidStr := Copy(Str, From, Size)
end;
<span style="color: rgba(51, 102, 255, 1)">function LeftStr(Const Str: String; Size: Word): String;</span>
begin
LeftStr := Copy(Str, 1, Size)
end;
</pre>
</div>
<p>并结合pos,copy,length函数使用;</p>
<p>但问题是中用Length来取字符长度时,会将汉字当成两个字节来计算,Copy把汉字当成两个来处理,可能截取半个汉字,那我们如何知道是否取的是汉字呢?是否把一个汉字取完整?</p>
<p>在delphi中自带ByteType函数对取出来的字符进行判断是一个单字符还是汉字的一部分!</p>
<p>mbLeadByte: 汉字的第一个字节<br>mbTrailByte: 汉字的第二个字节<br>mbSingleByte: 单个的字符,不是中文字符。<br>如果Copy出来的是汉字的第一个字节,就再多(或少)Copy一个,凑成完整的汉字。</p>
<p>以下的代码为转自https://www.cnblogs.com/pilybird/archive/2007/12/07/986711.html</p>
<div class="cnblogs_Highlighter">
<pre class="brush:delphi;gutter:true;">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 in LeadBytes then
begin
ChrLen := CharLength(AText,I)-1;
I:= I + ChrLen;
//说明AText不是一个中文字符的末尾
if I>ACount then
begin
IsMBCS := True;
BreakLen := I - ChrLen - 1;
Break;
end;
end;
//..
Inc(I);
end;
end;
//AText不是半个中文字符
if not IsMBCS then
Result := LeftStr(AText,ACount)
else
Result := LeftStr(AText,BreakLen);
end;
</pre>
</div>
<p> </p>
<p> </p><br><br>
来源:https://www.cnblogs.com/approx/p/12599897.html
頁:
[1]