Delphi 中英文字符怎么按固定长度截断


本文整理自网络,侵删。

 
固定aa长度bb

比如输入8,  返回"固定aa长"

用哪个方法?

type
      TFillPos = (fpLeft, fpMid, fpRight);
      //填充位置:左,中间,右
 
//Date: 2017-03-17
//Parm: 字符串;长度;填充方式;填充符;是否裁剪;单字节长度
//Desc: 使用nFixChar填充nStr,使其保持nWidth定长.
class function TStringHelper.FixWidth(const nStr: string; const nWidth: Word;
const nStyle: TFillPos; const nFixChar: Char; const nClip,nAnsiLen: Boolean): string;
var nAnsi: AnsiString;
    nLen,nHalf: Integer;
begin
  if nAnsiLen then
  begin
    {$IFDEF EnableThirdANSI}
    nAnsi := AnsiString.Create(nStr, TEncoding.ANSI);
    nLen := nAnsi.Length;
    {$ELSE}
    nAnsi := AnsiString(nStr);
    nLen := Length(nAnsi);
    {$ENDIF}
  end else
  begin
    nLen := Length(nStr);
    //wide string
  end;
 
  if nLen >= nWidth then
  begin
    if nClip and (nLen > nWidth) then
    begin
      if nAnsiLen then
           {$IFDEF EnableThirdANSI}
           Result := string(AnsiCopy(nAnsi, 1, nWidth))
           {$ELSE}
           Result := string(Copy(nAnsi, 1, nWidth))
           {$ENDIF}
      else Result := Copy(nStr, 1, nWidth);
    end else
    begin
      Result := nStr;
      //default
    end;
 
    Exit;
  end;
 
  nLen := nWidth - nLen;
  //not enough length
 
  case nStyle of
   fpLeft:
    begin
      Result := StringOfChar(nFixChar, nLen) + nStr;
    end;
   fpMid:
    begin 
      nHalf := Trunc(nLen / 2);
      Result := StringOfChar(nFixChar, nHalf) + nStr +
                StringOfChar(nFixChar, nLen - nHalf);
    end;
   fpRight: 
    begin
      Result := nStr + StringOfChar(nFixChar, nLen);      
    end;
  end;
end;
function CutCHNStr(S:String;Sum:integer):string;
var
  i,iCutLength : integer;
  sCuted:String;
  bIsDBCS:boolean;
begin
  sCuted := Copy(s, 1, Sum);
  iCutLength := Length(sCuted);
  bIsDBCS := False;
  //看看最后一个字符是不是中文的前半个字
  for  i := 1 to iCutLength do
  begin
    if bIsDBCS then
    begin
      bIsDBCS := False;
    end else if Windows.IsDBCSLeadByte(byte(sCuted[i])) then
    begin
      bIsDBCS := True;
    end;
  end;
  //如果最后一个字符是中文的话, 少截一个字元。
  if bIsDBCS then Dec(iCutLength);
  //截出确定长度的字符
  result:= Copy(s, 1, iCutLength);
end;
function odd_SubStr(s : AnsiString; len : Integer) : ansistring;
var
  w, r : widestring;
  i, p : Integer;
begin
  w := s;
  p := 0;
  for i := 1 to Length(w) do
  begin
    if p >= Len then
      Break;
    if Ord(w[i])>255 then
      Inc(p, 2)
    else
      inc(p, 1);
    r := r + w[i];
 
  end;
  Result := r;
end;
转自:http://bbs.2ccc.com/topic.asp?topicid=566596

相关阅读 >>

Delphi idhttp造成程序假死的解决办法

Delphi image 直接加载资源文件

Delphi stringgrid中回车换行

Delphi xe 遍历指定数据库,清空各表记录

Delphi链接自己的主页和邮件

Delphi [数据库连接字符串] access 连接字符串

fastmm5

Delphi字符串中取数字

Delphi timage 加上滚动条方法

Delphi xe7开发的直接以管理员模式启动cmd命令行界面

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...