How to cut a string to some desired number in delphi?
var s : string;
begin
s := 'your string with more than 40 characters...';
s := LeftStr(s, 40);
You can use SetLength
for this job:
SetLength(s, Min(Length(s), 40));
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.