13

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

4

4 回答 4

23
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…'

但是你必须肯定你的所有用户和他们的亲戚都支持这个不寻常的角色。

于 2013-02-18T12:27:39.110 回答
18

您可以SetLength用于此工作:

SetLength(s, Min(Length(s), 40));
于 2013-02-18T12:31:16.873 回答
14
var s : string;
begin   
   s := 'your string with more than 40 characters...';
   s := LeftStr(s, 40);
于 2013-02-18T12:29:45.727 回答
0

java 中的这个解决方案的启发,我的解决方案是这样的(缩短可能很长的路径)

   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;
于 2021-01-14T19:25:24.543 回答