How to cut a string to some desired number in delphi?

user1556433 picture user1556433 · Feb 18, 2013 · Viewed 19k times · Source

I have a database column which can take only 40 characters of a string. So when the length of string is greater than 40 characters, its giving me error. How can I cut/trim the string to 40 characters in delphi?

Answer

Andreas Rejbrand picture Andreas Rejbrand · Feb 18, 2013
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'

More fancy would be to add ellipsis if a string is truncated, to indicate this more clearly:

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 ...'

Or, for all Unicode lovers, you can keep two more original characters by using the single ellipsis character … (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…'

But then you must be positive that all your users and their relatives support this uncommon character.