user1556433
user1556433

Reputation:

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

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?

Upvotes: 13

Views: 26225

Answers (4)

MyICQ
MyICQ

Reputation: 1158

Inspired by this solution in java , my solution was something like this (shorten a path which may be very long)

   const
      maxlen = 77;   // found this by entering sample text

  begin
     headlineTemp := ExtractFileName(main.DatabaseFileName);
     if length(main.DatabaseFileName) > maxlen then
      begin
        pnlDBNavn.Caption :=
             MidStr(
                  main.DatabaseFileName, 1,
                           maxlen -3 - length(headlinetemp)
                ) + '...\' + headlineTemp;
      end
     else
         // name is shorter, so just display it
         pnlDBNavn.Caption := main.DatabaseFileName;
   end;

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612993

You can use SetLength for this job:

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

Upvotes: 19

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108963

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.

Upvotes: 25

Obl Tobl
Obl Tobl

Reputation: 5684

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

Upvotes: 14

Related Questions