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,这里只是转贴,备忘!

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值