16,742
社区成员
发帖
与我相关
我的任务
分享
function SplitString(aText: string; aLength: Integer): string;
function IsValidChar(aChar: Char): Boolean;
{
函数功能:将aText字符串按aLength长度进行分解,并折行显示。
算法介绍:如果aText字符串长度小于aLength,则返回整个字符串;
由于字符串中可能存在汉字,如果分解过程中末位正好遇到汉字
的第一个字节,截取结果可能出错,那么我们可以对每次截取
的最后一个字节进行判断,如果不属于英文字符、数字,那此
字节肯定和后一个字节组成一个汉字,必须在一起才能正确显示。
在此,设置一个offSet偏移量,每次遇到特殊情况,偏移量加一即可
备注:函数返回最后结果会多出回车换行符
}
function TForm1.SplitString(aText: string; aLength: Integer): string;
var
i, j, offSet: Integer;
begin
offSet := 0;
if Length(aText) < aLength then
Result := aText
else
for i := 0 to (Length(aText) div aLength) do //总共分几段
begin
for j := 1 to aLength do //将字符串按长度aLength逐个分解
begin
Result := Result + aText[i * aLength + j + offSet];
if j = aLength then
if not IsValidChar(aText[i * aLength + aLength]) then
begin
Result := Result + aText[i * aLength + aLength + offSet + 1];
Inc(offSet);
end;
end;
Result := Result + #13#10;
end;
end;
function TForm1.IsValidChar(aChar: Char): Boolean;
begin
if aChar in ['a'..'z', 'A'..'Z', '0'..'9'] then
Result := True
else
Result := False;
end;