如何在delphi中将字符串剪切为某个所需的数字?

时间:2013-02-18 12:26:59

标签: delphi delphi-xe2 delphi-7

我有一个数据库列,只能占用一个字符串的40个字符。所以当字符串的长度大于40个字符时,它会给我错误。如何在delphi中将字符串剪切/修剪为40个字符?

3 个答案:

答案 0 :(得分:18)

var
  s: string;
begin
  s := 'This is a string containing a lot of characters.'
  s := Copy(s, 1, 40);
  // Now s is 'This is a string containing a lot of cha'

如果字符串被截断,更多的想法是添加省略号,以更清楚地表明:

function StrMaxLen(const S: string; MaxLen: integer): string;
var
  i: Integer;
begin
  result := S;
  if Length(result) <= MaxLen then Exit;
  SetLength(result, MaxLen);
  for i := MaxLen downto MaxLen - 2 do
    result[i] := '.';
end;

var
  s: string;
begin
  s := 'This is a string containing a lot of characters.'
  s := StrMaxLen(S, 40)
  // Now s is 'This is a string containing a lot of ...'

或者,对于所有Unicode爱好者,您可以使用单个省略号字符保留两个以上的原始字符...(U + 2026:HORIZONTAL ELLIPSIS):

function StrMaxLen(const S: string; MaxLen: integer): string;
var
  i: Integer;
begin
  result := S;
  if Length(result) <= MaxLen then Exit;
  SetLength(result, MaxLen);
  result[MaxLen] := '…';
end;

var
  s: string;
begin
  s := 'This is a string containing a lot of characters.'
  s := StrMaxLen(S, 40)
  // Now s is 'This is a string containing a lot of ch…'

但是你必须肯定所有的用户及其亲属都支持这种不寻常的角色。

答案 1 :(得分:13)

您可以使用SetLength完成此项工作:

SetLength(s, Min(Length(s), 40));

答案 2 :(得分:12)

var s : string;
begin   
   s := 'your string with more than 40 characters...';
   s := LeftStr(s, 40);